[英]Matplotlib missing x tick labels
一旦运行下面的代码,第三个绘图ax3的x刻度标签将不会显示。 但是,我只删除了ax1和ax2的x刻度标签。 对日期显示在我的第三个绘图x3的x轴上的任何解决方案?
plt.figure()
ax1 = plt.subplot2grid((8,1),(0,0), rowspan=4, colspan=1)
ax1.yaxis.set_major_locator(mticker.MaxNLocator(nbins=10, prune='lower'))
plt.setp(ax1.get_xticklabels(), visible=False)
ax2 = plt.subplot2grid((8,1),(4,0), rowspan=2, colspan=1, sharex = ax1)
plt.setp(ax2.get_xticklabels(), visible=False)
ax3 = plt.subplot2grid((8,1),(6,0), rowspan=2, colspan=1, sharex = ax1)
ax3.xaxis.set_major_locator(mticker.MaxNLocator(10))
ax3.xaxis.set_minor_locator(mticker.MaxNLocator(20))
'''
# This has been ***removed*** in corrected version
for label in ax3.xaxis.get_ticklabels():
label.set_rotation(45)
plt.xlabel('Dates') #This label does not appear in the figure either
'''
ax3.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='upper'))
main.dropna(inplace=True)
main['sales1'].plot(ax=ax1)
main['sales2'].plot(ax=ax1)
cmain.plot(ax=ax2)
main[['rollsales1', 'rollsales2']].plot(ax=ax3)
'''
# This has been added to corrected version.
plt.setp(ax3.xaxis.get_label(), visible=True, text='Dates')
plt.setp(ax3.get_xticklabels(), visible=True, rotation=30, ha='right')
'''
plt.show()
在matplotlib中,使用sharex
或sharey
在版本2中默认情况下会关闭ticklabels。因此,您可以删除将标签可见性设置为False
的代码段。 另外,您无需遍历每个标签来更改参数,而是可以使用setp
一次性设置所有参数的参数。
我必须制作虚假数据来模拟您的图形,因此我的数据可能看起来很奇怪。
plt.figure()
ax1 = plt.subplot2grid((8,1),(0,0), rowspan=4, colspan=1)
ax2 = plt.subplot2grid((8,1),(4,0), rowspan=2, colspan=1, sharex=ax1)
ax3 = plt.subplot2grid((8,1),(6,0), rowspan=2, colspan=1, sharex=ax1)
ax1.yaxis.set_major_locator(mticker.MaxNLocator(nbins=10, prune='lower')
ax3.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='upper'))
main.dropna(inplace=True)
main['sales1'].plot(ax=ax1)
main['sales2'].plot(ax=ax1)
cmain.plot(ax=ax2)
main[['rollsales1', 'rollsales2']].plot(ax=ax3)
# set the xaxis label
plt.setp(ax3.xaxis.get_label(), visible=True, text='Dates')
# set the ticks
plt.setp(ax3.get_xticklabels(), visible=True, rotation=30, ha='right')
# turn off minor ticks
plt.minorticks_off()
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.