2

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:

Australia_data.set_index('date')['new_cases'].plot()
sns.set(font_scale=1.4)
Australia_data.set_index('date')['new_cases'].plot(figsize=(12, 10), linewidth=2.5)
plt.xlabel("Date", labelpad=15)
plt.ylabel("New Cases", labelpad=15)
plt.title("Australia daily COVID-19 cases", y=1.02, fontsize=22)
plt.axvline(dt.datetime(2020, 9, 21))

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

1
  • 1
    For me, axvline works fine if I use a list of Python datetime as x-axis. So since you call plot method here for a pd DataFrame, my suspicion is that this has to do how pandas treats datetime in plots. You might have to adjust the x-coordinate of axvline to that. Commented Feb 10, 2021 at 6:15

1 Answer 1

2

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

from datetime import datetime
from matplotlib import pyplot as plt
import pandas as pd

# dummy dataframe with a datetime index:
df = pd.DataFrame({'v': range(12)},
                  index=pd.date_range('2020', periods=12, freq='MS'))

df.plot()
# using a pandas timestamp:
plt.axvline(pd.Timestamp("2020-06-01"), color='r')
# using a datetime object:
plt.axvline(datetime(2020,8,1), color='g')

gives:

plot result

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

Sign up to request clarification or add additional context in comments.

1 Comment

Ah yep, using pandas.Timestamp fixed the issue, thanks so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.