如何在Matplotlib线形图中注释/标记假日?

2024-09-30 16:31:47 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能帮我在matplotlib(或Seaborn)线形图中注释假日吗?我试了几个循环,但我没能弄明白

这就是我的DF的样子(Aantal=Count,Feestdag=Holiday):

Dummy Dataset

我的目标是完成这种情节:

Plot with annotation


Tags: 目标dfmatplotlibcountseabornholiday情节样子
2条回答

您可以使用ax.annotate()方法。以下是一个完整的示例:

import random
import matplotlib.pyplot as plt

days = range(365)
# generate random numbers between 4000 and 5200
values = [4000+(random.random() * (5200 - 4000)) for _ in range(365)]

fig, ax = plt.subplots()
plt.plot(days, values)
plt.ylim(3000, 5400)
ax.set_xticks(days[::32])
ax.set_xticklabels(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
                    "Aug", "Sep", "Oct", "Nov", "Dec"])
plt.show()

它生成了这个图: enter image description here

现在,让我们在图中注释一些点。我们可以在plt.show()之前使用ax.annotate()方法来实现这一点,如下所示:

...
# annotate some points:
ax.annotate("100th data point", (days[100], values[100]), xytext=(days[100], values[100]-1000),
     arrowprops=dict(arrowstyle="->", connectionstyle="angle3,angleA=0,angleB=-90"))

ax.annotate("200th data point", (days[200], values[200]), xytext=(days[200], values[200]-1000),
            arrowprops=dict(facecolor='black', shrink=0.05))

# didn't use any arrow styles (just to show how it should look like)
ax.annotate("300th data point", (days[300], values[300]))
plt.show()

这将生成以下图表: enter image description here

使用ax.annotate()很容易。。。以下是我使用的参数:

  • 第一个参数是消息文本
  • 第二个参数是要注释的点的坐标
  • 第三个参数是文本将被写入的位置
  • 第四个论点是箭头应该是什么样子

有关更多信息,请查看official documentation中的ax.annotate()

感谢@Anwarvic!我找到了问题的解决方案!我做了这个循环(使用ax.annotate)以使其自动更新

fig, ax = plt.subplots(figsize=(15, 15))
dummy2019.plot(ax=ax)

for index, row in dummy2019.iterrows():
    if type(row['Feestdag']) is str:
        datum = index
        aantal = row['Aantal']
        feestdag = row['Feestdag']
        ax.annotate(feestdag, xy=(index, aantal),  xycoords='data',
                xytext=(80, -30), textcoords='offset points',
                arrowprops=dict(arrowstyle="->",
                                connectionstyle="arc3,rad=-0.2"))    

相关问题 更多 >