【问题标题】:Strange behavior of MultipleLocator() with subplots带有子图的 MultipleLocator() 的奇怪行为
【发布时间】:2014-07-14 18:35:44
【问题描述】:

这段代码有问题:

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

majorLocator   = MultipleLocator(0.1)
majorFormatter = FormatStrFormatter('%2.1f')

fig = plt.figure()
axes = []

for i in range(4):
    axes.append(fig.add_subplot(2,2,i+1))

for ax in axes:
    ax.yaxis.set_major_locator(majorLocator)
    ax.yaxis.set_major_formatter(majorFormatter)
    ax.set_ylim(0,1)

axes[-1].set_ylim(1,2) #If you comment this line all works fine.

plt.show()

在我的屏幕上出现了一个滴答问题。

但是,如果我评论 axes[-1].set_ylim(1,2) 行,所有刻度都会正确显示。这是一个错误吗?还是我做错了?

(matplotlib '1.3.0')

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    这是因为您在多个 y 轴对象之间共享同一个定位器对象。

    这不是错误,但它是一个微妙的问题,可能会引起很多混乱。文档可能对此更清楚,但定位器应属于单个axis

    您实际上可以共享同一个 Formatter 实例,但最好不要这样做,除非您知道后果(更改一个实例会影响所有实例)。

    不要回收相同的 LocatorFormatter 实例,而是为每个轴创建新实例:

    import matplotlib.pyplot as plt
    from matplotlib.ticker import MultipleLocator, FormatStrFormatter
    
    fig, axes = plt.subplots(2, 2)
    for ax in axes.flat:
        ax.yaxis.set(major_locator=MultipleLocator(0.1),
                     major_formatter=FormatStrFormatter('%2.1f'))
        ax.set_ylim(0, 1)
    
    axes[-1, -1].set_ylim(1, 2)
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-16
      • 2011-08-07
      • 1970-01-01
      • 2012-11-12
      • 2019-08-19
      • 2012-01-10
      相关资源
      最近更新 更多