Marking specific dates when visualizing a time series

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-18 12:14:30

问题


I have a time series that has a few years' worth of data, for example this:

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

ts = ts.cumsum()

ts.plot()

I also have two extra arrays: let's call the first

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

And the second

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

labels[i] contains the label for dates[i]. What I'd like to do is to display them in the time series graph so that they can be recognized. One possible visualization could be to display the date on the x axis, draw a vertical line starting from there and have the label either in a legend (with color coding) or somewhere next to the line.

The end result shouldn't be too different from this:


回答1:


Switching between pandas and matplotlib APIs can be confusing at first.

The solution: get the current axis and then use standard matplotlib API to annotate. This starts you off:

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()

This produces the image below, and you need to look into modifying titles, and text labels and their bounding boxes to the axis object:



来源:https://stackoverflow.com/questions/35906717/marking-specific-dates-when-visualizing-a-time-series

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!