在 Matplotlib 中注释时间序列图 [英] Annotate Time Series plot in Matplotlib
问题描述
我有一个日期(日期时间对象)的索引数组(x)和一个实际值数组(y:债券价格).做(在 iPython 中):
I have an index array (x) of dates (datetime objects) and an array of actual values (y: bond prices). Doing (in iPython):
plot(x,y)
生成一个完美的时间序列图,x 轴标有日期.到目前为止没有问题.但我想在某些日期添加文本.例如,在 2009 年 10 月 31 日,我希望显示文本事件 1",箭头指向该日期的 y 值.
Produces a perfectly fine time series graph with the x axis labeled with the dates. No problem so far. But I want to add text on certain dates. For example, at 2009-10-31 I wish to display the text "Event 1" with an arrow pointing to the y value at that date.
我已经通读了关于 text() 和 annotate() 的 Matplotlib 文档,但无济于事.它仅涵盖标准编号的 x 轴,我无法推断如何将这些示例用于解决我的问题.
I have read trough the Matplotlib documentation on text() and annotate() to no avail. It only covers standard numbered x-axises, and I can´t infer how to work those examples on my problem.
谢谢
推荐答案
Matplotlib 对日期使用内部浮点格式.
Matplotlib uses an internal floating point format for dates.
您只需要将日期转换为该格式(使用 matplotlib.dates.date2num
或 matplotlib.dates.datestr2num
),然后使用 annotate代码>像往常一样.
You just need to convert your date to that format (using matplotlib.dates.date2num
or matplotlib.dates.datestr2num
) and then use annotate
as usual.
举一个有点过于花哨的例子:
As a somewhat excessively fancy example:
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
x = [dt.datetime(2009, 05, 01), dt.datetime(2010, 06, 01),
dt.datetime(2011, 04, 01), dt.datetime(2012, 06, 01)]
y = [1, 3, 2, 5]
fig, ax = plt.subplots()
ax.plot_date(x, y, linestyle='--')
ax.annotate('Test', (mdates.date2num(x[1]), y[1]), xytext=(15, 15),
textcoords='offset points', arrowprops=dict(arrowstyle='-|>'))
fig.autofmt_xdate()
plt.show()
这篇关于在 Matplotlib 中注释时间序列图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!