Matplotlib缺少x刻度标签

时间:2017-03-15 20:54:06

标签: python pandas matplotlib python-3.6

一旦我运行下面的代码,第三个图表的x刻度标签ax3就不显示了。然而,我只删除了ax1和ax2的x刻度标签。有关日期的任何解决方案都出现在我的第三个图的轴x3轴上吗?

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

1 个答案:

答案 0 :(得分:1)

在matplotlib中,使用sharexsharey在版本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()

https://developer.apple.com/account/ios/certificate