如何使用 Matplotlib 在對數刻度上顯示次要刻度標籤?


要在對數刻度上使用 Matplotlib 顯示次要刻度標籤,我們可以採取以下步驟 -

  • 設定圖形大小並調整子圖之間和周圍的間距。
  • 使用 numpy 建立 xy 資料點。
  • 使用 plot() 方法繪製 xy 資料點
  • 使用 gca() 方法獲取當前座標軸。
  • 按名稱使用對數類設定 yscale
  • 使用 ick_params() 方法更改刻度和刻度標籤的外觀。
  • 使用格式字串設定次要座標軸格式化程式以格式化刻度。
  • 要顯示圖形,請使用 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()

輸出

更新日期: 2021 年 6 月 18 日

7 千 + 次瀏覽

開啟您的職業生涯

獲得認證

開始
廣告
© . All rights reserved.