使用 matplotlib 重叠折线图注释

时间:2021-03-20 08:29:21

标签: python pandas matplotlib annotations line-plot

我有带时间序列数据的 df,我想注释行尾。

id      Date        Buddies Score
42949   2021-03-11  Walter  58
42954   2021-03-11  Travis  143
42985   2021-03-12  Buck    438
43002   2021-03-12  Donald  248
43018   2021-03-12  Charlie 312
43045   2021-03-12  Johnny  2590
43069   2021-03-12  Walter  56
43074   2021-03-12  Travis  133
43105   2021-03-13  Buck    423
43122   2021-03-13  Donald  255
43138   2021-03-13  Charlie 309
43165   2021-03-13  Johnny  2484
43189   2021-03-13  Walter  52
43194   2021-03-13  Travis  120
...

我绘制它们。

fig, ax = plt.subplots()
date ='2020-12-01'
people = [
    "Buck",
    "Johnny",
    "Walter",
    "Charlie",
    "Donald",
    "Travis"
    
]

for person in people:
    ax = df[(df["Date"]>= date)& 
                (df["Buddies"]== person)].plot(ax = ax, kind='line', x='Date', y='Score', label=person)

并注释我的行尾

for line, name in zip(ax.lines, people):
    y = line.get_ydata()[-1]    
    ax.annotate(name, xy=(1,y), xytext=(15,0), color=line.get_color(), 
                xycoords = ax.get_yaxis_transform(), textcoords="offset points",
                size=14, va="center", 
                arrowprops=dict(arrowstyle="-",
                                    shrinkA=0, shrinkB=0,
                                    connectionstyle="arc3", 
                                    color='black')
               )

plt.show()

结果是这张图:

Score plot

我正在努力解决的问题是行尾重叠。我知道我必须根据其他项目位置更改 xytext 值,但我不知道该怎么做。

0 个答案:

没有答案
相关问题