Pandas Dataframe Line Plot: Display Date on X-axis Accurately
To accurately display dates on the x-axis of a Pandas Dataframe line plot, it's important to understand the incompatibilities between the datetime utilities of Pandas and Matplotlib.
Matplotlib's dates module handles datetime objects as floating point numbers that represent time in days since 0001-01-01 UTC, with an offset of 1. This differs from the format used by Pandas, leading to potential issues.
To resolve this problem, one can disable Pandas' datetime handling capabilities and instead rely on Matplotlib's formatting options. This can be achieved by setting x_compat=True when plotting the Dataframe:
test.plot(x_compat=True)
However, this approach also means sacrificing Pandas' sophisticated date formatting capabilities. To overcome this limitation, consider using Matplotlib's formatting directly:
ax.xaxis.set_major_locator(dates.DayLocator()) ax.xaxis.set_major_formatter(dates.DateFormatter('%d\n\n%a'))
By using the DayLocator and DateFormatter from Matplotlib's dates module, you can customize the date display without compromising accuracy.
Additionally, you can invert the x-axis and auto-format the dates:
ax.invert_xaxis() plt.gca().autofmt_xdate(rotation=0, ha="center")
This approach provides flexibility in date formatting while ensuring compatibility between Pandas and Matplotlib.
The above is the detailed content of How to Display Dates Accurately on the X-axis of a Pandas Dataframe Line Plot?. For more information, please follow other related articles on the PHP Chinese website!