Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีแสดงเครื่องหมาย Minor Tick Labels บนมาตราสเกล Log ใน Matplotlib


เพื่อแสดงเครื่องหมาย Minor Tick Labels บนมาตราสเกล Log (log-scale) ใน Matplotlib ให้ทำตามขั้นตอน:

  • กำหนดขนาดรูปและปรับระยะห่างระหว่างและรอบซับพล็อต
  • สร้างจุดข้อมูล x และ y ด้วย NumPy
  • พล็อต x และ y ด้วย plot()
  • ดึงแกนปัจจุบันด้วย gca()
  • ตั้งค่า yscale เป็น log
  • เปลี่ยนลักษณะ ticks และ tick label ด้วย tick_params()
  • ตั้งค่า formatter สำหรับ minor axis ด้วย format strings
  • ใช้ show() เพื่อแสดงรูป

ตัวอย่าง

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.linspace(-2, 2, 10)
y = np.exp(x)
plt.plot(x, y)
ax = plt.gca()
ax.set_yscale('log')
plt.tick_params(axis='y', which='minor')
ax.yaxis.set_minor_formatter(FormatStrFormatter("%.1f"))
plt.show()

ผลลัพธ์

วิธีแสดงเครื่องหมาย Minor Tick Labels บนมาตราสเกล Log ใน Matplotlib