簡體   English   中英

在 Matplotlib 中設置對數刻度 plot 中的主要 yticks

[英]setting major yticks in log-scale plot in Matplotlib

我想創建一個 plot,其中垂直刻度為對數刻度。 我希望主要刻度(帶有數字標簽)位於1e-91e-61e-31e0 ,我希望次刻度位於 10 的每個冪,即1e-91e-81e-7 , ... , 1e-1 , 1e0 換句話說,我總共想要 4 個主要刻度(帶有數字標簽)和 10 個次要刻度。 我使用以下蠻力方法讓它工作:

fig, ax = plt.subplots()

ax.set_yscale('log')

ax.set_ylim([1e-9,1])
ax.set_yticks(np.logspace(-9,0,10))
ax.set_yticklabels([r'$10^{-9}$','','',r'$10^{-6}$','','',r'$10^{-3}$','','',r'$10^{0}$'])

plt.show()

但我想盡可能避免使用 MathText,因為這會弄亂圖形的字體,而且還需要我手動記下刻度線,這樣如果我更改刻度線的位置,工作量會很大。

有更自動的方法嗎? 我試過查看ax.yaxis.set_minor_locator(LogLocator(base=10, numticks=10))但我無法為我的案例找出正確的參數值。

您可以將所有刻度設置為 10 的冪:

ax.yaxis.set_major_locator(FixedLocator(locs = np.logspace(-9, 0, 10)))

然后你可以刪除指數的絕對值不是 3 的倍數的刻度,這樣你只保留1e-91e-61e-31e0刻度:

fig.canvas.draw()

yticks = ax.yaxis.get_major_ticks()
for tick in yticks:
    if np.log10(tick.get_loc())%3 != 0:
        tick.label1.set_visible(False)

完整代碼

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


x = np.linspace(0, 20, 21)
y = np.exp(-x)


fig, ax = plt.subplots()

ax.plot(x, y, marker = 'o')

ax.set_yscale('log')
ax.yaxis.set_major_locator(FixedLocator(locs = np.logspace(-9, 0, 10)))

fig.canvas.draw()

yticks = ax.yaxis.get_major_ticks()
for tick in yticks:
    if np.log10(tick.get_loc())%3 != 0:
        tick.label1.set_visible(False)

plt.show()

在此處輸入圖像描述


您還可以對1e-91e-61e-31e0 (帶標簽)使用主刻度,對其他(不帶標簽)使用次刻度:

ax.set_yscale('log')
ax.yaxis.set_major_locator(FixedLocator(locs = np.logspace(-9, 0, 4)))
ax.yaxis.set_minor_locator(FixedLocator(locs = np.logspace(-9, 0, 10)))

fig.canvas.draw()

yticks = ax.yaxis.get_minor_ticks()
for tick in yticks:
    if np.log10(tick.get_loc())%3 != 0:
        tick.label1.set_visible(False)

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM