Strange behavior of MultipleLocator() with subplots

陌路散爱 提交于 2021-02-15 06:55:12

问题


I'm having trouble with this piece of code:

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()

In my screen a tick issue appears.

enter image description here

But if I comment the line axes[-1].set_ylim(1,2) all the ticks are properly displayed. Is this a bug? Or I am doing it wrong?

(matplotlib '1.3.0')


回答1:


This is because you're sharing the same locator object between multiple y-axis objects.

It's not a bug, but it is a subtle issue that can cause a lot of confusion. The documentation could probably be more clear about this, but locators are expected to belong to a single axis.

You actually can share the same Formatter instance, but it's probably better not to, unless you're aware of the ramifications (changes to one will affect all).

Instead of recycling the same Locator and Formatter instances, create new ones for each axis:

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()

enter image description here



来源:https://stackoverflow.com/questions/24743410/strange-behavior-of-multiplelocator-with-subplots

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!