0

I have a problem setting axvline over my plot for dataframe.

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 159 entries, 0 to 158
Data columns (total 6 columns):
 #   Column       Non-Null Count  Dtype         
---  ------       --------------  -----         
 0   index        159 non-null    int64         
 1   Year         159 non-null    int64         
 2   Week         159 non-null    object        
 3   Week_Number  159 non-null    int64         
 4   Week_Start   159 non-null    datetime64[ns]
 5   Incidents    159 non-null    int64         
dtypes: datetime64[ns](1), int64(4), object(1)

This is my code:

from pandas import DataFrame
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(20, 4))
df=Alldata
Year=Alldata['Year']
Week=Alldata['Week']
Week_Number=Alldata['Week_Number']
Week_Start=Alldata['Week_Start']
Incidents=Alldata['Incidents']
Dataset = list(zip(Year, Week, Week_Number,Week_Start, Incidents))
df = DataFrame(data = Dataset, columns = ['Year', 'Week', 'Week_Number','Week_Start', 'Incidents'])
df['Incidents'].plot(legend = True, label = 'Incidents')
plt.xticks(df.index,df["Week_Start"].values)
unique_years, ind = np.unique(df["Year"].values,return_index=True)
plt.xticks(df.index[ind], unique_years)
#ax.axvline(pd.to_datetime('2020-03-18'), color='r', linestyle='--', lw=2)
#ax.axvline(pd.to_datetime('2021-06-05'), color='b', linestyle='--', lw=2)
plt.show()

For some reason I get a graph like this:

enter image description here

Without my axvline, I get a normal graph as desired:

enter image description here

Could someone please help me with my axvline?

Gaurang
  • 18
  • 3
  • Look at where you are plotting the vertical line. It's so far to the right that it compresses the entire domain into a couple of pixels – Mad Physicist Jul 18 '22 at 21:28
  • Not sure why though... – Mad Physicist Jul 18 '22 at 21:29
  • Can you supply a DF with one or two columns and 10 rows that reproduces the issue? – Mad Physicist Jul 18 '22 at 21:29
  • Could you try using `datetime.datetime` instead of `pd.to_datetime`? e.g., `ax.axvline(datetime.datetime('2020-03-18'), color='r', linestyle='--', lw=2)` Matplotlib likely doesnt know how to convert `pd.Timestamp` to `datetime`. – dubbbdan Jul 18 '22 at 22:22
  • Looking through the docs, it looks like you should initialize the axis for dates prior to plotting. [ax.axis_date](https://matplotlib.org/stable/api/_as_gen/matplotlib.axis.Axis.axis_date.html#matplotlib.axis.Axis.axis_date) – dubbbdan Jul 18 '22 at 23:06
  • also might be good to specify `ax=ax` in the `df.plot` method. e.g., `df['Incidents'].plot(legend = True, label = 'Incidents', ax = ax)` – dubbbdan Jul 18 '22 at 23:08
  • @dubbbdan I get a TypeError: an integer is required (got type str). Something very strange going on here. Maybe my data structure isnt correct! – Gaurang Jul 19 '22 at 12:18
  • My Dates over the matplot graphs seem to start at 1970-01-1 and end on 1970-06-10. While the data shows the date from 2019-01-01 onwards till 2021-05-06. How can I reset the dates to given timings? – Gaurang Jul 19 '22 at 12:49
  • oh sorry about the syntax issue. the correct syntax for would be populating the method with integer arguments `datetime.datetime(2020,3,18)`. Alternatively you could try the the [`.to_pydatetime`](https://pandas.pydata.org/docs/reference/api/pandas.Timestamp.to_pydatetime.html) method. e.g, `pd.to_datetime('2020-03-18').to_pydatetime()` – dubbbdan Jul 19 '22 at 15:36
  • I also dont think you can use `plt.xticks(df.index,df["Week_Start"].values)` for datetime axis. you would need to set the format using a [matplotlib date.formatter](https://stackoverflow.com/a/33746112/2864250) – dubbbdan Jul 19 '22 at 15:54

0 Answers0