【问题标题】:Matplotlib: setting x-limits also forces tick labels?Matplotlib:设置 x-limits 也会强制刻度标签?
【发布时间】:2017-08-08 07:30:47
【问题描述】:

我刚刚升级到 matplotlib 2.0,我觉得我在吃药。我正在尝试制作一个对数线性图,y 轴在线性刻度上,x 轴在 log10 刻度上。以前,下面的代码可以让我准确地指定我想要刻度的位置,以及我想要它们的标签是什么:

import matplotlib.pyplot as plt

plt.plot([0.0,5.0], [1.0, 1.0], '--', color='k', zorder=1, lw=2)

plt.xlim(0.4,2.0)
plt.ylim(0.0,2.0)

plt.xscale('log')

plt.tick_params(axis='x',which='minor',bottom='off',top='off')

xticks = [0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0]
ticklabels = ['0.4', '0.6', '0.8', '1.0', '1.2', '1.4', '1.6', '1.8', '2.0']
plt.xticks(xticks, ticklabels)

plt.show()

但是在 matplotlib 2.0 中,这现在导致我得到一组重叠的刻度标签,其中 matplotlib 显然想要自动创建刻度:

但如果我注释掉“plt.xlim(0.4,2.0)”行并让它自动确定轴限制,则没有重叠的刻度标签,我只得到我想要的:

但这不起作用,因为我现在有无用的 x 轴限制。

有什么想法吗?

编辑:对于将来搜索互联网的人来说,我越来越相信这实际上是 matplotlib 本身的一个错误。我恢复到 v. 1.5.3。只是为了避免这个问题。

【问题讨论】:

    标签: matplotlib


    【解决方案1】:

    重叠的额外刻度标签源自图中存在的一些次要刻度标签。要摆脱它们,可以将次要格式化程序设置为NullFormatter

    plt.gca().xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
    

    问题的完整代码可能如下所示

    import matplotlib.pyplot as plt
    import matplotlib.ticker
    import numpy as np
    
    x = np.linspace(0,2.5)
    y = np.sin(x*6)
    plt.plot(x,y, '--', color='k', zorder=1, lw=2)
    
    plt.xlim(0.4,2.0)
    
    plt.xscale('log')
    
    xticks = [0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0]
    ticklabels = ['0.4', '0.6', '0.8', '1.0', '1.2', '1.4', '1.6', '1.8', '2.0']
    plt.xticks(xticks, ticklabels)
    
    plt.gca().xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
    
    plt.show()
    

    以下代码可能更直观,因为它没有将 xticklabels 设置为字符串,我们使用FixedLocatorScalarFormatter
    此代码生成与上面相同的图。

    import matplotlib.pyplot as plt
    import matplotlib.ticker
    import numpy as np
    
    x = np.linspace(0,2.5)
    y = np.sin(x*6)
    plt.plot(x,y, '--', color='k', zorder=1, lw=2)
    
    plt.xlim(0.4,2.0)
    plt.xscale('log')
    
    xticks = [0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0]
    
    xmajorLocator = matplotlib.ticker.FixedLocator(locs=xticks) 
    xmajorFormatter = matplotlib.ticker.ScalarFormatter()
    plt.gca().xaxis.set_major_locator( xmajorLocator )
    plt.gca().xaxis.set_major_formatter( xmajorFormatter )
    plt.gca().xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2019-07-02
      • 2015-09-04
      • 1970-01-01
      • 2019-07-03
      • 2019-11-18
      • 2022-01-01
      • 2013-12-30
      • 2012-03-14
      • 1970-01-01
      相关资源
      最近更新 更多