How to Display Only Year and Month on a Matplotlib Datetime Axis?

Susan Sarandon
Release: 2024-11-01 18:58:02
Original
692 people have browsed it

How to Display Only Year and Month on a Matplotlib Datetime Axis?

Modifying the Formatting of Datetime Axis

When visualizing time series data, the formatting of the datetime axis is crucial for readability and conveying the intended information. This article aims to address a common challenge faced by programmers: modifying the axis formatting to display only the year and month.

Example

Consider a series with a datetime index:

2014-01-01     7
2014-02-01     8
2014-03-01     9
2014-04-01     8
Copy after login

Plotting the series using plt.plot(series.index, series.values) results in an axis that includes hours, minutes, and seconds:

[Image of the graph with hours, minutes, and seconds]

To remove this unnecessary information and obtain a cleaner axis, we use:

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

# Set the major and minor ticks to use the desired format
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m"))</code>
Copy after login

This ensures that the x-axis displays only the year and month.

Result

[Image of the graph with only the year and month]

By implementing this solution, you can effectively change the formatting of a datetime axis to meet your visualization needs.

The above is the detailed content of How to Display Only Year and Month on a Matplotlib Datetime Axis?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!