I'm pulling my hair to display a series with matplotlib.
I'm working with python 2.7. I have a pandas Dataframe with dates. I converted dates to datetime and I'm trying to display a plot without success.
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime, date
#I imported df before
type(df)
<class 'pandas.core.frame.DataFrame'>
# The dataframe
AnneeObs MoisObs JourObs NbFluxEntrant
0 2019 8 19 763
1 2019 8 1 1098
... ... ... ... ...
655 2017 11 1 428
656 2017 11 13 1530
[657 rows x 4 columns]
# To convert dates to datetime
for i in range(0,len(df)):
df.loc[i,"dateObs"] = date(year=df.iloc[i,0], month=df.iloc[i,1],
day=df.iloc[i,2])
df['dateObs'] = pd.DatetimeIndex(df['dateObs'])
# To order by dates
df = df.sort_values("dateObs", ascending=True)
df2 = df[["dateObs", "NbFluxEntrant"]]
df2bis = df2.copy()
df2bis = df2bis.set_index('dateObs')
df2bis
# The new dataframe
NbFluxEntrant
dateObs
2017-11-01 428
2017-11-02 931
... ...
2019-08-18 243
2019-08-19 763
[657 rows x 1 columns]
# Maybe it's too much...
df2bis.index = pd.to_datetime(df2bis.index)
type(df2bis.index)
<class 'pandas.core.indexes.datetimes.DatetimeIndex'>
# I tried to display it but...
df2bis.plot()
However, it doesn't work :
Fail to execute line 1: df2bis.plot()
ValueError: view limit minimum 0.0 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units
I tried others code but nothing good :
df2bis.plot(x="dateObs", y="NbFluxEntrant")
df2bis.plot(x=df2bis.index.values, y="NbFluxEntrant")
Do you have any suggestions ?
Thanks in advance
EDIT : I tried another code that doesn't work :
import matplotlib
dates = matplotlib.dates.date2num(df2bis.index)
dates
array([736634., 736635.,..., 737289., 737290.])
matplotlib.pyplot.plot_date(dates, df2bis["NbFluxEntrant"])
ValueError: view limit minimum 0.0 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units
Hmmm...
Using the DateFormatter module from matplotlib, you can specify the format that you want to use for the date using the syntax: "%X %X" where each %X element represents a part of the date as follows: %Y - 4 digit year with upper case Y. %y - 2 digit year with lower case y. %m - month as a number with lower case m.
To create a real-time plot, we need to use the animation module in matplotlib. We set up the figure and axes in the usual way, but we draw directly to the axes, ax , when we want to create a new frame in the animation.
I faced a similar issue. You could try this:
df2bis.set_index('dateObs', inplace=True)
df2bis.index = pd.to_datetime(df2bis.index)
df2bis.plot()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With