Home > Backend Development > Python Tutorial > How can I format a datetime axis in matplotlib to show only year and month?

How can I format a datetime axis in matplotlib to show only year and month?

DDD
Release: 2024-10-27 18:46:30
Original
267 people have browsed it

How can I format a datetime axis in matplotlib to show only year and month?

Adjusting the Format of a Datetime Axis

In a scenario where you have a series with a datetime index that you wish to visualize, you may encounter a situation where the graph displays timestamps including hours, minutes, and seconds despite your preference for a simpler format like "yyyy-mm" or "2016 March."

To address this issue and achieve the desired formatting, we can leverage the functionalities provided by matplotlib. In particular, the datetime axis can be customized using formatters. These formatters allow you to specify how the tick labels on the x-axis should be displayed.

Here's an example that demonstrates the use of formatters:

<code class="python">import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# Sample data with hourly timestamps
N = 30
drange = pd.date_range("2014-01", periods=N, freq="H")
np.random.seed(365)
values = {'values':np.random.randint(1,20,size=N)}
df = pd.DataFrame(values, index=drange)

# Create a plot with incorrect formatting
fig, ax = plt.subplots()
ax.plot(df.index, df.values)
ax.set_xticks(df.index)

# Use formatters to achieve the desired formatting
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m"))
plt.xticks(rotation=90)

# Display the updated plot with the desired formatting
plt.show()</code>
Copy after login

In this example, we first create a sample DataFrame with hourly timestamps. We then use the DateFormatter from matplotlib.dates to specify that the tick labels on the x-axis should be in the format "%Y-%m", which represents the year and month only. Finally, we call xticks to rotate the tick labels for better readability.

By implementing this approach, you can effectively customize the format of your datetime axis, ensuring that it aligns with your desired display requirements.

The above is the detailed content of How can I format a datetime axis in matplotlib to show only year and month?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template