Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
944 views
in Technique[技术] by (71.8m points)

python - Strange behavior of MultipleLocator() with subplots

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...