在可视化时间序列时标注特定日期

5

我有一个时间序列,其中包含几年的数据,例如这样:

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))

ts = ts.cumsum()

ts.plot()

我可以帮助您翻译以下内容:

我还有两个额外的数组:让我们称第一个为

dates = [pd.datetime("2000-12-01"), pd.datetime("2001-01-03")]

和第二个

labels = ["My birthday", "My dad's birthday"]

labels[i] 包含 dates[i] 的标签。我想要做的是在时间序列图中显示它们,以便它们可以被识别。一个可能的可视化方式是在 x 轴上显示日期,从那里开始绘制一条垂直线,并将标签放在图例中(带有颜色编码)或线旁边的某个位置。

最终结果与此不应有太大差异:

ExampleGraph


你想知道如何绘制和标记一条竖线吗? - tom10
只需在谷歌上搜索 matplotlib vline label - roadrunner66
1个回答

8

在pandas和matplotlib之间切换API可能一开始会让人感到困惑。

解决方法:获取当前轴,并使用标准的matplotlib API进行注释。以下是入门指南:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

ts = pd.Series(np.random.randn(1000),
               index=pd.date_range('1/1/2000',
               periods=1000))

ts = ts.cumsum()
ts.plot()

label_list = [
    (pd.to_datetime("2001-05-01"), 'My\nbirthday', 'r'),
    (pd.to_datetime("2001-10-16"), "Dad's\nbirthday", 'b')
]

ax = plt.gca()

for date_point, label, clr in label_list:
    plt.axvline(x=date_point, color=clr)
    plt.text(date_point, ax.get_ylim()[1]-4, label,
             horizontalalignment='center',
             verticalalignment='center',
             color=clr,
             bbox=dict(facecolor='white', alpha=0.9))

plt.show()

这会生成下面的图像,您需要查看修改 标题文本标签及其边界框以适应轴对象:

example image


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接