2017-03-15 155 views
0

一旦我運行下面的代碼,第三個繪圖ax3的x刻度標籤就不會顯示出來。但是,我只刪除了ax1和ax2的x刻度標籤。有任何解決方案讓日期出現在我的第三個繪圖ax3的x軸上?Matplotlib缺少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() 
+1

您在這裏有太多的代碼。請提供**最少**,完整且可驗證的示例。 – James

+0

縮短到我認爲問題可能出現的地方。感謝您的意見。 – econ99

+0

你使用的是什麼版本的matplotlib? – James

回答

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

enter image description here

+0

它的工作原理!對此,我真的非常感激!我在頂部添加了兩個數字(x軸日期是每月),首先顯示結果,然後放大。作爲最終跟進問題,我怎麼能填充更多的x軸?在第二幅圖中,放大時如何顯示月份? – econ99

+0

在調整圖形之間的垂直間距之前,嘗試使用'plt.tight_layout()'。還請記住將問題標記爲已回答:) – James

+0

我嘗試使用'plt.tight_layout()',但由於某些原因,它仍然無法正常工作。 – econ99