问题描述
我有一个日期(日期时间对象)的索引数组(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.
一个过于夸张的例子:
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中注释时间序列图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!