2
我有一个通用绘图类,它使用matplotlib来生成(png)可能有多个y轴,但总是显示日期的单个(共享)x轴的绘图。matplotlib:仅显示主要x轴上的次要刻度标签
这是与x轴标签格式化交易的方法,包括:
def format_xaxis(self, axis, primary):
steps = (1,2,3,4,6,12)
step = steps[min(len(self.dates) // 1000, 5)]
axis.set_axisbelow(True)
axis.xaxis.grid(b=True, which='minor', color='0.90', linewidth=0.5)
axis.xaxis.set_minor_locator(MonthLocator(bymonth=range(1,13,step)))
axis.xaxis.set_major_locator(YearLocator())
if primary:
axis.xaxis.set_major_formatter(DateFormatter(fmt='%b %y'))
axis.xaxis.set_minor_formatter(DateFormatter(fmt='%b'))
else:
plt.setp(axis.get_xticklabels(), visible=False)
与输入:
- 主要是一个布尔值,表示如果这是主轴
- 轴是matplotlib轴实例
我想要的(并期望从上述方法)是th在唯一的主轴上有标签,主要标签仅为月份和次要标签月份。
会发生什么情况是只有主标签显示在主轴上,次标签完全不显示。
如果我改变在过去的6行:
axis.xaxis.set_major_locator(YearLocator())
axis.xaxis.set_major_formatter(DateFormatter(fmt='%b %y'))
axis.xaxis.set_minor_formatter(DateFormatter(fmt='%b'))
if not primary:
plt.setp(axis.get_xticklabels(), visible=False)
那么小的标签显示在所有轴。
如何仅在主x轴上显示次要x轴刻度标签?
编辑:
二号代码块的工作使用KevinG的建议:
axis.xaxis.set_major_locator(YearLocator())
axis.xaxis.set_major_formatter(DateFormatter(fmt='%b %y'))
axis.xaxis.set_minor_formatter(DateFormatter(fmt='%b'))
if not primary:
plt.setp(axis.get_xticklabels(minor=False), visible=False)
plt.setp(axis.get_xticklabels(minor=True), visible=False)
感谢KevinG。你的代码不能按原样工作,但是你的建议反正把它应用到了我的替代代码中(见上面的编辑) –
很高兴我能提供帮助。但有一件事让我对这个解决方案的逻辑感到厌烦......似乎它打开了所有xaxis的次要xaxis标签,但主要是......如果所有的xaxis都是相同的和覆盖的(这必须是你的情况!),但如果你只有一个x轴,并且它被标记为主要的,或者每个x轴具有不同的位置,将会中断。 – KevinG
你说得对,我所有的x轴都是一样的。我没有测试过它,但如果只有一个主轴,它也应该工作 - 在这种情况下,'visible = False'行不会被执行(这是正确的)。 –