Home >Backend Development >Python Tutorial >How to Display Only Year and Month on a Matplotlib Datetime Axis?

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

Susan Sarandon
Susan SarandonOriginal
2024-11-01 18:58:02747browse

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

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>

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!

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