Skip to content
Advertisement

Adding a verticle line using axvline in matplotlib based on datetime data

I am trying to add a vertical line using axvline to a line chart using matplotlib and am running into a recurring error. I have been looking for a solution and read what was suggested here How to draw vertical lines on a given plot in matplotlib but they do not look specifically at using datetime. A solution is discussed here matplotlib plot_date() add vertical line at specified date and a similar answer is given here How do you plot a vertical line on a time series plot in Pandas? which are helpful, but when I implement the advice (the advice is basically to add plt.axvline(dt.datetime(2020, 9, 21)) my line chart squashes all of the data into a single spot and adds a vertical line right at the end of the chart like so.

Here is my code:

JavaScript

Really not sure what is going wrong here, any advice would be greatly appreciated!

Advertisement

Answer

You should be able to use both a pandas.Timestamp and a Python datetime object as x-coordinate for the axvline:

JavaScript

gives:

plot result

Version: Python 3.8.7 x86-64, pandas 1.2.1, matplotlib 3.3.3

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement