如何在 Python Matplotlib 中新增第三級刻度?


要在 Python Matplotlib 中新增第三級刻度,我們可以採取以下步驟:

  • 設定圖形大小並調整子圖之間和周圍的填充。
  • 使用 numpy 建立 ts 資料點。
  • 建立一個圖形和一組子圖。
  • 使用 plot() 方法繪製 ts
  • 建立共享 Y 軸的雙軸。
  • 使用 plot() 方法在第一個軸上繪製 ts
  • 設定 X 軸刻度位置。
  • 建立主刻度值 majors、次刻度值 minors 和第三級刻度值 (thirds)
  • 使用 majorsminors 和第三級刻度值 (thirds) 設定主刻度和次刻度定位器。
  • 使用 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()

輸出

更新於: 2021年7月8日

284 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.