【问题标题】:Minor ticks on logarithmic axis in MatplotlibMatplotlib 中对数轴上的小刻度
【发布时间】:2012-09-19 11:28:37
【问题描述】:

我有一个带有对数 x 轴和 y 轴的散点图(因为我主要对两者的较低值感兴趣)。

但是,我希望刻度标签采用十进制格式,而不是 10^x。

我正在使用这个:

# axis limits:
ax.set_xlim(xmin=0, xmax = 1.2)
ax.set_ylim(ymin=0,ymax=1000)

# log scales:
ax.set_yscale('log')
ax.set_xscale('log')

# set y-ticks:
ax.set_yticks((1,10,100,1000))
ax.set_yticklabels(("1","10","100","1000"))

这可行(尽管引入 ax.set_yscale('log')ax.set_xscale('log') 会引发以下警告(知道这是怎么回事吗?):

Warning (from warnings module):
  File "C:\Python27\lib\site-packages\numpy\ma\core.py", line 3785
warnings.warn("Warning: converting a masked element to nan.")
UserWarning: Warning: converting a masked element to nan.

但是当我在 x 轴上尝试相同时,我得到一个 MaskError:

# set x-ticks:
ax.set_xticks((0, 0.2, 0.4, 0.8, 1))
ax.set_xticklabels(("0", "0.2", "0.4", "0.8", "1"))

[snip long long traceback]
File "C:\Python27\lib\site-packages\numpy\ma\core.py", line 3795, in __int__
  raise MaskError, 'Cannot convert masked element to a Python int.'
MaskError: Cannot convert masked element to a Python int.

我认为这与次要与主要刻度有关。我曾尝试使用ticker,但最后总是遇到相同的错误。

如果有任何帮助,我将不胜感激!

回答后编辑: 通过替换解决问题

ax.set_yticks((1,10,100,1000))
ax.set_yticklabels(("1","10","100","1000"))
ax.set_xticks((0, 0.2, 0.4, 0.8, 1))
ax.set_xticklabels(("0", "0.2", "0.4", "0.8", "1"))

ax.yaxis.set_major_formatter(FormatStrFormatter('%1.0f'))
ax.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
ax.xaxis.set_minor_formatter(FormatStrFormatter('%.1f'))

【问题讨论】:

    标签: matplotlib


    【解决方案1】:

    您可以将ticker 用作:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.ticker import FormatStrFormatter
    
    fig = plt.figure(1, [5,4])
    ax = fig.add_subplot(111)
    
    ax.plot( range(1,100) , range(1,100) ,  color='#aaaaff')
    ax.set_xscale('log')
    ax.xaxis.set_major_formatter(FormatStrFormatter('%.03f'))
    plt.show()
    

    【讨论】:

    • 嗯。我可以发誓我尝试过这个,它抛出了同样的错误......但它有效!谢谢!
    猜你喜欢
    • 2013-02-21
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 2023-01-28
    • 2017-08-13
    • 2013-01-20
    • 2016-11-05
    相关资源
    最近更新 更多