MultipleLocator() 与子图的奇怪行为 [英] Strange behavior of MultipleLocator() with subplots
问题描述
这段代码有问题:
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.
但是,如果我注释 axes [-1] .set_ylim(1,2)
行,则所有刻度线都将正确显示.这是一个错误吗?还是我做错了?
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')
(matplotlib '1.3.0')
推荐答案
这是因为您在多个 y 轴对象之间共享同一个定位器对象.
This is because you're sharing the same locator object between multiple y-axis objects.
这不是错误,但它是一个细微的问题,可能引起很多混乱.文档可能对此更清楚,但定位器应属于单个 axis
.
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
.
您实际上可以共享相同的 Formatter
实例,但是最好不要共享,除非您知道后果(更改为1会影响全部).
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).
代替回收相同的 Locator
和 Formatter
实例,而是为每个轴创建一个新实例:
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()
这篇关于MultipleLocator() 与子图的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!