Home  >  Article  >  Backend Development  >  How to Format the Datetime Axis of a Matplotlib Graph to Display Year and Month Only?

How to Format the Datetime Axis of a Matplotlib Graph to Display Year and Month Only?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 00:26:31176browse

How to Format the Datetime Axis of a Matplotlib Graph to Display Year and Month Only?

Changing the Datetime Axis Format on a Matplotlib Graph

When plotting a time series with a datetime index, it is often desirable to format the x-axis labels to display a specific level of detail, such as year-month combinations. This can be achieved by using the DateFormatter class from the matplotlib.dates module.

Problem:

A user wants to plot a series indexed by datetime, but the graph displays time values down to the second, resulting in cluttered labels. The desired format is to show only year and month (e.g., "2014-01" or "2016 March").

Solution:

To achieve the desired formatting, follow these steps:

  1. Import the necessary modules: numpy (np), pandas (pd), matplotlib.pyplot (plt), and matplotlib.dates (mdates).
  2. Create a sample DataFrame with a datetime index and random values.
  3. Create a figure and axes using plt.subplots().
  4. Plot the series by calling ax.plot(df.index, df.values).
  5. Specify the x-axis ticks using ax.set_xticks(df.index).
  6. Use DateFormatter to specify the major and minor tick formatters. In this example, mdates.DateFormatter("%Y-%m") is used to display dates in the format "YYYY-MM".
  7. Rotate the x-axis tick labels (optional) using _ = plt.xticks(rotation=90) .

The resulting graph will display the series data with the desired datetime axis formatting, showing only the year and month values.

The above is the detailed content of How to Format the Datetime Axis of a Matplotlib Graph to Display Year and Month Only?. 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