Search code examples
python-3.xmatplotlibannotations

Annotate date on the xaxis


I have the following code:

import pandas as pd
from pandas_datareader import data as web
import matplotlib.pyplot as plt
import datetime as datetime
start = datetime.date(2008,1,1)
end = datetime.date.today()
start1 = datetime.date(2019,1,1)
data = web.get_data_yahoo("AAPL",start, end)
data1 = web.get_data_yahoo("AMZN", start1, end1)
ax = data.plot(y ="Close")
data1.plot(y = "Close", ax=ax)

The resulting chart looks like this:

enter image description here

How can i annotate the orange line which is AMZN so i can see the date. Is there a way a straight line could be drawn down and have its date shown on the xaxis?


Solution

  • If you plot the date sting on the x-axis I think you will get a clumpy result. What about adding a text notation to the side:

    ax.text(start1, data1.Close[0], start1, ha='right', va='top', rotation=90)
    

    Here's the complete code if you want to add a vertical line as well:

    import pandas as pd
    from pandas_datareader import data as web
    import matplotlib.pyplot as plt
    import datetime as datetime
    start = datetime.date(2008,1,1)
    end = datetime.date.today()
    start1 = datetime.date(2019,1,1)
    data = web.get_data_yahoo("AAPL",start, end)
    data1 = web.get_data_yahoo("AMZN", start1, end)
    ax = data.plot(y ="Close")
    data1.plot(y = "Close", ax=ax)
    
    ylims = ax.get_ylim()
    ax.vlines(start1, ylims[0], data1.Close[0], linestyles='--')
    ax.text(start1, data1.Close[0], start1, ha='right', va='top', rotation=90)
    ax.set_ylim(ylims)
    

    enter image description here