优雅地为pandas绘图添加不重叠文本注释

4 投票
1 回答
1959 浏览
提问于 2025-04-18 02:14

我有一个包含一些事件和计数的 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()

因为这个数据框里有重复的日期时间索引,所以标注的文字会重叠在一起:

overlappinglabels

有没有更好的方法来展示这些信息呢?

可能的解决方案: 我想我通过随机化 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)

enter image description here

1 个回答

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)

撰写回答