Annotate Time Series plot in Matplotlib

前端 未结 1 1697
刺人心
刺人心 2020-12-01 01:16

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)

Produce

相关标签:
1条回答
  • 2020-12-01 02:18

    Matplotlib uses an internal floating point format for dates.

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

    enter image description here

    0 讨论(0)
提交回复
热议问题