【问题标题】:Annotate data value at the end of line matplotlib在 matplotlib 行的末尾注释数据值
【发布时间】:2020-03-29 10:43:38
【问题描述】:

我正在尝试将数据值添加到 matplotlib 行的末尾。这是我的代码:

fig, ax = plt.subplots(1, 1)
anz_df.plot(legend=True, ax=ax, figsize= (16,8))
ax.set_title("Number of confirmed cases between Australian' States vs New Zealand")
ax.set_ylabel('Number of confirmed Cases')
ax.set_xlabel('Date')
for line, name in zip(ax.lines, anz_df.columns):
    y = line.get_ydata()[-1]
    ax.annotate(name, xy=(1,y), xytext=(6,0), color=line.get_color(), 
                xycoords = ax.get_yaxis_transform(), textcoords="offset points",
                size=14, va="center")

这是结果:

但是,我想在每行的末尾添加数据值。

另外,我可以像这样可视化支持鼠标悬停的数据的库:

感谢任何想法。

【问题讨论】:

  • 关于悬停 - 检查 Plotly。
  • 我会看看这些库。谢谢

标签: python matplotlib annotate


【解决方案1】:

您应该能够使用timedelta(days=1)(来自datetime 库)以此处描述的方式为日期添加一天:Adding 5 days to a date in Python

这样

y = line.get_ydata()[-1]
x = line.get_xdata()[-1]+timedelta(days=1) # or something reasonable
ax.annotate('{:d}'.format(y), xy=(x,y)  ...

对于悬停,您可以使用 plotly 或 bokeh,后者可能更容易。

【讨论】:

  • 您好 jgf,感谢您的评论。但是,我想在每行的末尾添加数据值(案例数)。
  • @MikeB 不只是y 的数据值吗?所以不是name 你可以注释y 格式化为字符串? “行”是指数据行,对吗?不是其他线路。
  • 你是对的。我确实更改为 y 但有些标签只是重叠,所以我更改为 Plotly 。顺便说一句,谢谢。
猜你喜欢
  • 2018-08-20
  • 2012-09-29
  • 1970-01-01
  • 2023-03-27
  • 2011-03-13
  • 1970-01-01
  • 2014-01-27
  • 1970-01-01
相关资源
最近更新 更多