Home > Backend Development > Python Tutorial > How to Display Dates Accurately on the X-axis of a Pandas Dataframe Line Plot?

How to Display Dates Accurately on the X-axis of a Pandas Dataframe Line Plot?

Patricia Arquette
Release: 2024-10-29 18:01:03
Original
664 people have browsed it

How to Display Dates Accurately on the X-axis of a Pandas Dataframe Line Plot?

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)
Copy after login

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'))
Copy after login

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")
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template