旋转Matplotlib注释文本的轴:Python

9
我正在尝试注释所有的数据点,但是在注释时文本重叠在一起。
fig = plt.figure(figsize=(70,2))
fig.autofmt_xdate()
plt.style.use('ggplot')
axess= plt.subplot(1,1,1)
axess.plot_date(idx2,stock2,'--')

axess.set_title("Doc_ID:7377")
axess.set_ylabel('1 - Online, 0 - Offline')

for i,txt in enumerate(date_match_df['service_name_'].tolist()):
    print(txt)
    axess.annotate(txt,(mdates.date2num(idx2[i]),stock2[i]),)
axess.yaxis.grid(True)
axess.xaxis.grid(True)

axess.xaxis.set_major_locator(dates.MonthLocator())
axess.xaxis.set_major_formatter(dates.DateFormatter('\n\n%b-%Y'))

axess.xaxis.set_minor_locator(dates.DayLocator())
axess.xaxis.set_minor_formatter(dates.DateFormatter('\n%d-%a'))
plt.tight_layout()

fig.savefig('happynewyear.svg')

图表看起来像这样: 图表图片 如何旋转文本?

方法.annotate()具有默认值为零的rotation参数。尝试使用rotation=90。 - swatchai
1个回答

18

.annotate() 方法的其他参数将传递给 Text,因此您可以这样做:

for i,txt in enumerate(date_match_df['service_name_'].tolist()):
    print(txt)
    axess.annotate(txt,(mdates.date2num(idx2[i]),stock2[i]), ha='left', rotation=60)

在你的代码中更改的地方是在结尾处添加了ha='left', rotation=60


如果同一日期有多个点,我们可以在文本之间加入行间距吗? - Sriram Arvind Lakshmanakumar
我不确定在你的情况下增加重叠文本的可读性的最佳方法是什么。我认为也许文本出现在每个注释框中,你需要明确位置。现在看起来怎么样?也许最好创建一个新的SO问题,以获得更多关于这个问题的答案。 - Thomas Fauskanger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接