Home  >  Article  >  Backend Development  >  How to Correctly Plot Dates on the X-Axis in Matplotlib?

How to Correctly Plot Dates on the X-Axis in Matplotlib?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-17 13:51:02887browse

How to Correctly Plot Dates on the X-Axis in Matplotlib?

Understanding Date Plotting in matplotlib

Plotting information against dates can be a common task when working with time-series data. However, converting and plotting dates can occasionally lead to errors.

The Issue: Converting and Plotting Dates

In the example provided, the user encountered a "ValueError: year is out of range" error while attempting to plot dates on the x-axis. The issue arose from the conversion process, specifically when using num2date.

The Solution: Utilizing the plot Function

To resolve this issue, consider using the plot function instead of plot_date. This method takes a list of dates and automatically recognizes them as dates, allowing you to bypass the conversion step.

Step 1: Convert Dates to datetime.date Objects

Convert the date strings to instances of datetime.date for easier handling. For example:

<code class="python">import datetime as dt

dates = ['01/02/1991', '01/03/1991', '01/04/1991']
x = [dt.datetime.strptime(d, '%m/%d/%Y').date() for d in dates]</code>

Step 2: Configure X-Axis for Date Formatting

Set up the x-axis to display dates correctly using DateFormatter and DayLocator from matplotlib.dates:

<code class="python">import matplotlib.pyplot as plt
import matplotlib.dates as mdates

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())</code>

Step 3: Generate the Plot

Finally, plot the data using the set-up x-axis and the y-axis data:

<code class="python">plt.plot(x, y)
plt.gcf().autofmt_xdate()</code>

This method eliminates the conversion errors and correctly plots the dates on the x-axis, providing a clear representation of time-based data.

The above is the detailed content of How to Correctly Plot Dates on the X-Axis in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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