Sometimes, we want to add a line plot display date on x-axis with a Python Pandas Dataframe, we can use matplotlib.
In this article, we’ll look at how to add a line plot display date on x-axis with a Python Pandas Dataframe.
How to add a line plot display date on x-axis with a Python Pandas Dataframe?
To add a line plot display date on x-axis with a Python Pandas Dataframe, we can use matplotlib.
For instance, we write
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
df = pd.DataFrame({'date':['20170527','20170526','20170525'],'ratio1':[1,0.98,0.97]})
df['date'] = pd.to_datetime(df['date'])
usePandas=True
#Either use pandas
if usePandas:
df = df.set_index('date')
df.plot(x_compat=True)
plt.gca().xaxis.set_major_locator(dates.DayLocator())
plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%d\n\n%a'))
plt.gca().invert_xaxis()
plt.gcf().autofmt_xdate(rotation=0, ha="center")
# or use matplotlib
else:
plt.plot(df["date"], df["ratio1"])
plt.gca().xaxis.set_major_locator(dates.DayLocator())
plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%d\n\n%a'))
plt.gca().invert_xaxis()
plt.show()
to call plt.gca
to create the axes.
And then we call invert_xaxis
to invert the x-axis.
Then we create the figure with gcf
.
Finally, we call plt.show
to show the plot.
Conclusion
To add a line plot display date on x-axis with a Python Pandas Dataframe, we can use matplotlib.