![](/img/trans.png)
[英]How to get the desired labels on ticks on the x-axis in a matplotlib plot?
[英]Changing x-axis labels in errorbar plot: no attribute 'get_xticklabels'
我正在嘗試繪制一些數據,主要的繪制信息是
ax1 = plt.errorbar(df1.index, df1['Mean'],
yerr=df1['SD'], color='black', linestyle='-')
ax2 = plt.errorbar(df2.index, df2['Mean'],
yerr=df2['SD'], color='grey', linestyle='-')
問題是每個數據幀索引都是整體的5%增量(即df1索引是df2的是0,5,10 ... 100),結果是該圖試圖在x軸上填充40個標簽
我嘗試了幾種不同的方法,但到目前為止都沒有奏效。 例如,嘗試旋轉標簽並減小字體大小,例如:
plt.setp(ax1.get_xticklabels(), rotation='vertical', fontsize=7)
回報
AttributeError: 'ErrorbarContainer' object has no attribute 'get_xticklabels'
如果嘗試使用tick_params
更改ax1和tick_params
的x軸,則會收到相同的錯誤
我認為可能是因為該圖將x軸視為分類,但我對如何解決它感到困惑?
理想情況下,我只想顯示ax1和ax2的0%,25%,50%,75%和100%標簽,但此時我很樂意旋轉它們,使它們看起來更好。
問題是您使用的是( errorbar
)繪圖的手柄,而不是軸的手柄。 有兩種方法可以獲取軸的手柄:
plt.gca()
獲取當前軸的句柄。 一個例子:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.errorbar([0,1,2], [0,1,2], yerr=[.01,.05,.1])
ax.errorbar([0,1,2], [0,2,4], yerr=[.01,.05,.1])
plt.setp(ax.get_xticklabels(), rotation='vertical', fontsize=7)
plt.show()
這將導致:
如果要使用當前軸的手柄,也可以使用:
plt.setp(plt.gca().get_xticklabels(), rotation='vertical', fontsize=7)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.