我在处理这段代码时遇到了问题:
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')
请您参考如下方法:
这是因为您在多个 y 轴对象之间共享同一个定位器对象。
这不是错误,但它是一个可能引起很多困惑的微妙问题。文档可能对此更清楚,但定位器应属于单个 axis。
您实际上可以共享相同的 Formatter 实例,但最好不要共享,除非您知道后果(对其中一个的更改会影响所有)。
与其回收相同的 Locator 和 Formatter 实例,不如为每个轴创建新实例:
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()
