How to Display Dates Correctly on the X-Axis of a Pandas DataFrame Line Plot?

Patricia Arquette
Release: 2024-10-28 08:49:02
Original
880 people have browsed it

How to Display Dates Correctly on the X-Axis of a Pandas DataFrame Line Plot?

Pandas Dataframe line plot display date on xaxis

Problem:

When attempting to plot a Pandas DataFrame with dates on the x-axis, the matplotlib library produces inaccurate formatting and dates that do not correspond correctly to the data.

Answer:

The incompatibility between the datetime utilities of Pandas and Matplotlib is the root cause of this problem. Pandas uses a non-standard floating-point representation for datetime objects, which is incompatible with Matplotlib's own date formatting methods.

Solution:

To resolve this issue, there are two possible approaches:

  1. Disable Pandas date formatting:

    By setting x_compat=True when plotting the DataFrame, Pandas will use Matplotlib's internal date formatting mechanisms, allowing for more precise control over the x-axis formatting.

  2. Use Matplotlib exclusively for plotting and formatting:

    Instead of relying on Pandas for date plotting, you can use Matplotlib's own methods to handle the date values and formatting. This provides greater flexibility and allows you to customize the date formatting as needed.

Here's an updated example that demonstrates both approaches:

<code class="python">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')
    ax = df.plot(x_compat=True, figsize=(6, 4))
    ax.xaxis.set_major_locator(dates.DayLocator())
    ax.xaxis.set_major_formatter(dates.DateFormatter('%d\n\n%a'))
    ax.invert_xaxis()
    ax.get_figure().autofmt_xdate(rotation=0, ha="center")

# or use Matplotlib
else:
    fig, ax = plt.subplots(figsize=(6, 4))
    ax.plot('date', 'ratio1', data=df)
    ax.xaxis.set_major_locator(dates.DayLocator())
    ax.xaxis.set_major_formatter(dates.DateFormatter('%d\n\n%a'))
    fig.invert_xaxis()

plt.show()</code>
Copy after login

By using either of these approaches, you can effectively display datetime values on the x-axis of a Pandas DataFrame plot with accurate formatting.

The above is the detailed content of How to Display Dates Correctly 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