【问题标题】:Edit tick labels in logarithmic axis在对数轴上编辑刻度标签
【发布时间】:2018-01-05 21:47:09
【问题描述】:

我正在尝试编辑刻度标签,但即使在设置刻度之后,我也不断得到科学记数法。这是一个 MWE:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(9, 7))
fig.subplots_adjust(left=0.11, right=0.95, top=0.94)

ax.ticklabel_format(style='plain')

plt.plot([1,4],[3,6] )

ax.set_yscale('log')
ax.set_xscale('log')

ax.set_xticks([0.7,1,1.5,2,2.5,3,4,5])

ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())

产生这个情节

正如您所见,ax.ticklabel_format(style='plain') 似乎不起作用,因为我不断获得科学记数法的刻度标签,并且在使用 ax.set_xticks 时,旧的刻度标签仍然存在。我看了this 主题,似乎问题出在刻度的选择上,如果我使用例如 0.3 而不是 0.7 作为第一个刻度,它可以工作,但是我需要在这个特定范围内做一个绘图并使用对数刻度。

有什么解决办法吗?

【问题讨论】:

    标签: python-2.7 matplotlib axis-labels


    【解决方案1】:

    实际上,您的代码正在做您需要的事情,问题是 minor 刻度中的标签保持不受影响并与主要刻度重叠

    您可以简单地添加以下行:

    ax.get_xaxis().set_minor_formatter(matplotlib.ticker.NullFormatter())
    

    完整代码:

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots(figsize=(9, 7))
    fig.subplots_adjust(left=0.11, right=0.95, top=0.94)
    
    ax.ticklabel_format(style='plain')
    
    plt.plot([1,4],[3,6] )
    
    ax.set_yscale('log')
    ax.set_xscale('log')
    
    ax.set_xticks([0.7,1,1.5,2,2.5,3,4,5])
    ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
    ax.get_xaxis().set_minor_formatter(matplotlib.ticker.NullFormatter())
    

    【讨论】:

    • 你是绝对正确的,现在它完美运行。谢谢。
    猜你喜欢
    • 2021-10-29
    • 2011-03-28
    • 2012-10-06
    • 2012-05-08
    • 1970-01-01
    • 2014-10-07
    • 2012-03-14
    • 2019-03-02
    相关资源
    最近更新 更多