加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 使用不重叠的文本优雅地注释pandas plot

发布时间:2020-12-20 13:41:51 所属栏目:Python 来源:网络整理
导读:我有下面的pandas数据框,其中包含一些事件和计数,我希望在图表中绘制和注释事件详细信息: Date Time Time Zone Currency Event Importance Actual Forecast Previous Count VolumeDateTime 2014-04-09 00:30:00 Wed Apr 9 00:30 GMT aud AUD Westpac Consum
我有下面的pandas数据框,其中包含一些事件和计数,我希望在图表中绘制和注释事件详细信息:

Date    Time    Time Zone   Currency    Event   Importance  Actual  Forecast    Previous    Count   Volume
DateTime                                            
2014-04-09 00:30:00  Wed Apr 9   00:30   GMT     aud     AUD Westpac Consumer Confidence     Medium  0.3%    NaN     -0.7%   198     7739
2014-04-09 00:30:00  Wed Apr 9   00:30   GMT     aud     AUD Westpac Consumer Conf Index     Low     99.7    NaN     99.5    198     7279
2014-04-09 01:30:00  Wed Apr 9   01:30   GMT     aud     AUD Investment Lending  Low     4.4%    NaN     -3.7%   172     21297
2014-04-09 01:30:00  Wed Apr 9   01:30   GMT     aud     AUD Home Loans  Medium  2.3%    1.5%    0.0%    172     22197
2014-04-09 01:30:00  Wed Apr 9   01:30   GMT     aud     AUD Value of Loans (MoM)    Low     1.9%    NaN     1.6%    172     22197

我正在使用以下代码绘制数据帧(df):

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

temp=df[df['Count'].notnull()]
#temp=temp[temp['Importance']=="High"]

x = temp.index
y = temp.Count
z = temp.Event
g = temp.Importance
v = temp.Volume

fig,ax = plt.subplots(figsize=(15,8))
ax.plot_date(x,y,linestyle='--')

for i in range(len(x)):
    if g[i]=="Medium":
        ax.annotate(z[i]+' '+'Volume: '+str(v[i]),(mdates.date2num(x[i]),y[i]),xytext=(15,15),textcoords='offset points',arrowprops=dict(arrowstyle='-|>'))


fig.autofmt_xdate()
plt.show()

由于数据框包含重复 – 日期时间 – 索引,带注释的文本将以重叠的方式出现:

有没有更好的显示方式?

可能的方法:
我想通过随机化xytext值来设法得到一个好的情节

ax.annotate(z[i]+' '+'Volume: '+str(v[i]),xytext=(5+randint(1,50),5+randint(1,50)),arrowprops=dict(arrowstyle='-|>'),rotation=0)

解决方法

您似乎可以通过旋转注释文本来解决重叠注释.这可以通过添加’rotation = 90’来完成

ax.annotate(z[i]+' '+'Volume: '+str(v[i]),rotation=90)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读