Home >Backend Development >Python Tutorial >How to Correctly Plot Dates on the X-Axis 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!