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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3