【发布时间】:2020-10-07 01:17:58
【问题描述】:
.在现有线程 (Annotate Time Series plot in Matplotlib) 中,他们注释了单个折线图。我在注释多个共享同一轴的折线图之后:我有两个数据框,如下所示:
df:
Value
Week
2020-04-05 0.330967
2020-04-12 1.307075
2020-04-19 2.406805
2020-04-26 2.562565
2020-05-03 2.868995
2020-05-10 5.174968
2020-05-17 5.734933
2020-05-24 6.903961
2020-05-31 7.205925
2020-06-07 9.960470
2020-06-14 11.106135
2020-06-21 12.356842
2020-06-28 13.247175
2020-07-05 13.600287
2020-07-12 15.098775
2020-07-19 16.754835
2020-07-26 18.596575
2020-08-02 20.118878
2020-08-09 21.168825
2020-08-16 21.201978
2020-08-23 21.784821
2020-08-30 22.329772
2020-09-06 23.981835
2020-09-13 23.981835
2020-09-20 23.981835
df2:
Value
Date
2020-09-27 29.003255
2020-10-04 29.642155
2020-10-11 30.872583
2020-10-18 32.492713
2020-10-25 33.436226
2020-11-01 35.187827
2020-11-08 35.589155
2020-11-15 37.185094
2020-11-22 37.575597
2020-11-29 39.273018
2020-12-06 40.047140
2020-12-13 41.621320
2020-12-20 42.563794
2020-12-27 43.750932
2021-01-03 44.823089
2021-01-10 45.797449
2021-01-17 47.109407
2021-01-24 48.045107
2021-01-31 49.472744
2021-02-07 50.355325
2021-02-14 51.717578
2021-02-21 52.602765
2021-02-28 53.886987
2021-03-07 54.888933
2021-03-14 56.108036
2021-03-21 57.226216
2021-03-28 58.345462
我使用以下代码将这两个数据框绘制为折线图:
我想绘制这些数据框并希望在图表上显示数据标签。为此,我正在关注这篇文章 (https://queirozf.com/entries/add-labels-and-text-to-matplotlib-plots-annotation-examples) 在折线图上绘制标签。由于我有两个不同的数据框,所以我尝试了一种稍微不同的方法来获取 xs 和 ys 的值。这是我的代码:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
ys = np.array([df.index,df2.index])
xs = np.array([df.Value,df2.Value])
fig, ax = plt.subplots(figsize=(12,6))
ax.plot(df.index,df['Value'],'-',color='c')
ax.plot(df2.index,df2['Value'],'-',color='g')
for x,y in zip(xs,ys):
label = "{:.2f}".format(y)
plt.annotate(label, (x,y), textcoords="offset points", ha='center')
plt.show()
当我运行上面的代码时,它给了我以下错误:
TypeError: unsupported format string passed to DatetimeIndex.__format__
谁能指导我哪里出错了?
【问题讨论】:
-
这能回答你的问题吗? Annotate Time Series plot in Matplotlib
-
@steven 我在同一张图上标注了多个折线图。
-
如果您不需要静态数据标签,请尝试改用Plotly。您只需将鼠标悬停在交互中的数据点上即可获得它们的确切值。
-
您应该尝试打印每个步骤的输出以查看您在做什么。至少对我来说,有很多东西在你的代码中已经没有意义了。错误是因为您试图将日期格式化为带 2 位小数的浮点数,而我认为您打算用您的值来做到这一点
标签: python python-3.x matplotlib