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

วิธีเพิ่มระดับ Tick ที่ 3 ใน Python Matplotlib

ในการเพิ่มระดับ tick ที่ 3 ใน Python Matplotlib เราสามารถทำตามขั้นตอนต่อไปนี้:

  • ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots
  • สร้างจุดข้อมูล t และ s ด้วย numpy
  • สร้าง figure และชุด subplots
  • พลอต t และ s ด้วยเมธอด plot()
  • สร้าง twin Axes แบ่งปันแกน Y
  • พลอต t และ s ด้วยเมธอด plot() บนแกนหนึ่ง
  • ตั้งค่าตำแหน่ง X-axis tick
  • สร้าง majors, minors และค่า tick ระดับที่ 3 (thirds)
  • ตั้งค่า major และ minor ticks locator ด้วย majors, minors และค่า tick ระดับ 3 (thirds)
  • ตั้งค่าความยาว ticks ด้วย tick_params()
  • พลอตเส้นแนวนอนสีเทา
  • เพื่อแสดงรูป ใช้เมธอด show()

ตัวอย่าง

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

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

t = np.arange(0.0, 100.0, 0.1)
s = np.sin(0.1 * np.pi * t) * np.exp(-t * 0.01)

fig, ax = plt.subplots()
plt.plot(t, s)

ax1 = ax.twiny()
ax1.plot(t, s)
ax1.xaxis.set_ticks_position('bottom')

majors = np.linspace(0, 100, 6)
minors = np.linspace(0, 100, 11)
thirds = np.linspace(0, 100, 101)

ax.xaxis.set_major_locator(matplotlib.ticker.FixedLocator(majors))
ax.xaxis.set_minor_locator(matplotlib.ticker.FixedLocator(minors))
ax1.xaxis.set_major_locator(matplotlib.ticker.FixedLocator([]))
ax1.xaxis.set_minor_locator(matplotlib.ticker.FixedLocator(thirds))

ax1.tick_params(which='minor', length=2)
ax.tick_params(which='minor', length=4)
ax.tick_params(which='major', length=6)

ax.grid(which='both', axis='x', linestyle='--')
plt.axhline(color='gray')
plt.show()

ผลลัพธ์

วิธีเพิ่มระดับ Tick ที่ 3 ใน Python Matplotlib