


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>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

Using python in Linux terminal...

Fastapi ...

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...
