Home >Backend Development >Python Tutorial >How to Format a Datetime Axis in Matplotlib for Better Readability?

How to Format a Datetime Axis in Matplotlib for Better Readability?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 15:39:30685browse

How to Format a Datetime Axis in Matplotlib for Better Readability?

Formatting a Datetime Axis

When plotting a Series with a datetime index, the x-axis may display hours, minutes, and seconds along with the year and month. To simplify the graph's readability, it is possible to remove this excessive time information.

Consider a sample Series:

2014-01-01     7
2014-02-01     8
2014-03-01     9
2014-04-01     8

Plotting this Series would initially display a graph with a crowded x-axis.

import matplotlib.pyplot as plt
import pandas as pd

series = pd.Series([7, 8, 9, 8], index=pd.date_range('2014-01', periods=4, freq='MS'))
plt.plot(series.index, series.values)
plt.show()

To resolve this issue, Matplotlib's formatters can be utilized to control the display format of the x-axis ticks.

import numpy as np
import matplotlib.dates as mdates

# generate data
N = 30
drange = pd.date_range("2014-01", periods=N, freq="MS")
np.random.seed(365)  # for reproducible values
values = {'values':np.random.randint(1,20,size=N)}
df = pd.DataFrame(values, index=drange)

# plot
fig, ax = plt.subplots()
ax.plot(df.index, df.values)

# set tick formatters
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m"))
plt.xticks(rotation=90)
plt.show()

By specifying the "%Y-%m" format string, the x-axis labels now display the year and month in a simplified format.

The above is the detailed content of How to Format a Datetime Axis in Matplotlib for Better Readability?. 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