【问题标题】:Annotating gracefully pandas plot with texts that do not overlap用不重叠的文本优雅地注释熊猫图
【发布时间】:2014-04-10 17:07:54
【问题描述】:

我有以下 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]), (mdates.date2num(x[i]), y[i]), xytext=(5+randint(1,50), 5+randint(1,50)), 
            textcoords='offset points', arrowprops=dict(arrowstyle='-|>'), rotation=0)

【问题讨论】:

    标签: python matplotlib pandas


    【解决方案1】:

    看来你可以通过旋转注释文本来解决重叠注释。这可以通过添加 'rotation=90' 来完成

    ax.annotate(z[i]+' '+'Volume: '+str(v[i]), (mdates.date2num(x[i]), y[i]), xytext=(15, 15), 
                textcoords='offset points', arrowprops=dict(arrowstyle='-|>'), rotation=90)
    

    【讨论】:

    • 看起来并没有消除重叠文本的问题,尤其是当您使用静态值进行旋转时。即使使用随机值,它看起来也不太好:ax.annotate(z[i]+' '+'Volume: '+str(v[i]), (mdates.date2num(x[i]), y[i]), xytext=(1, 1), textcoords='offset points', arrowprops=dict(arrowstyle='-|>'), rotation=randint(4.5,9)*10)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 2019-01-12
    • 1970-01-01
    相关资源
    最近更新 更多