Reformat the timeline of the pandas time series plot with matplotlib

When I set_major_formatter () after df.plot (), I was suffering from the problem that the year and month notation of xtick was broken, but I solved it, so I made a note.

Premise

pandas:0.24.2 matplotlib:3.1.0

Data preparation

import pandas as pd
import numpy as np

N = 100
x = np.random.rand(N)
y = x**2

df = pd.DataFrame(
    index=pd.date_range('2020-01-01', periods=N, freq='D'),
    data=dict(x=x, y=y)
)
df.head()

image.png

No problem case

#Use pandas plot function
df.plot()

image.png If the DataFrame index is DatetimeIndex, it will automatically format the tick. If this format is OK, that's fine.

Problematic case

import matplotlib.dates as mdates

#Use pandas plot function
ax = df.plot()

#Reformat
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m/%d'))

image.png

The display for% Y is strange. What is 0051 years ... According to the site below, the cause is that the datetime utilities of pandas and matplotlib are not compatible. https://code-examples.net/ja/q/2a2a615

solution

import matplotlib.dates as mdates

# x_Pass the compat option. This suppresses the automatic adjustment of ticks.
ax = df.plot(x_compat=True)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m/%d'))

image.png

% Y is now in 2020!

Is x_compat an abbreviation for x_compatibility? According to the official documentation, x_compat is a parameter that suppresses the automatic adjustment of ticks. https://pandas.pydata.org/pandas-docs/stable/user_guide/visualization.html#suppressing-tick-resolution-adjustment

If there is a smarter way, I would appreciate it if you could teach me.

Recommended Posts

Reformat the timeline of the pandas time series plot with matplotlib
Time series plot / Matplotlib
Plot CSV of time series data with unixtime value in Python (matplotlib)
Plot the Nikkei Stock Average with pandas
Align the size of the colorbar with matplotlib
Plot multiple maps and data at the same time with Python's matplotlib
Convenient time series aggregation with TimeGrouper in pandas
Increase the font size of the graph with matplotlib
View details of time series data with Remotte
The basis of graph theory with matplotlib animation
Visualize the behavior of the sorting algorithm with matplotlib
Type conversion of multiple columns of pandas DataFrame with astype at the same time
2-axis plot with Matplotlib
3D plot with matplotlib
Find the sum of unique values with pandas crosstab
Drawing on Jupyter using the plot function of pandas
Adjust the ratio of multiple figures with the matplotlib gridspec
Calculate the time difference between two columns with Pandas DataFrame
Let's execute the command on time with the bot of discord
[Python] I want to make a 3D scatter plot of the epicenter with Cartopy + Matplotlib!
[In 3 lines] Plot the population pyramid (bar graph of age group / gender) with Pandas alone
Stackable bar plot with matplotlib
Let's visualize the number of people infected with coronavirus with matplotlib
[Python] Plot time series data
Graph time series data in Python using pandas and matplotlib
Change the style of matplotlib
I wrote the basic operation of matplotlib with Jupyter Lab
Animate the alpha and beta values of the world's top market cap stocks with pandas + matplotlib
How to plot a lot of legends by changing the color of the graph continuously with matplotlib
The Power of Pandas: Python
Basic calculation of pandas to enjoy Hakone Ekiden while competing with the best members of all time
Manage the overlap when drawing scatter plots with a large amount of data (Matplotlib, Pandas, Datashader)
Read the coordinates of the plot on the graph with Python-matplotlib (super beginner)
How to extract features of time series data with PySpark Basics
Format the CSV file of "National Holiday" of the Cabinet Office with pandas
I wrote the basic operation of Pandas with Jupyter Lab (Part 1)
[Statistics] [Time series analysis] Plot the ARMA model and grasp the tendency.
I wrote the basic operation of Pandas with Jupyter Lab (Part 2)
Calculation of time series customer loyalty
Create plot animation with Python + Matplotlib
Plot the spread of the new coronavirus
Easy time series prediction with Prophet
Extract the maximum value with pandas.
Versatile data plotting with pandas + matplotlib
Process the result of% time,% timeit
Time series plot started ~ python edition ~
Differentiation of time series data (discrete)
Unravel the mystery of matplotlib specgram
Time series analysis 3 Preprocessing of time series data
Continuously color with matplotlib scatter plot
About the size of matplotlib points
Cases using pandas plot, cases using (pure) matplotlib plot
Lognormal probability plot with Python, matplotlib
Adjust the bin width crisply and neatly with the histogram of matplotlib and seaborn
The story of having a hard time introducing OpenCV with M1 MAC
I made a mistake in fetching the hierarchy with MultiIndex of pandas
Forecasting time series data with Simplex Projection
[Python] Set the graph range with matplotlib
Adjust the spacing between figures with Matplotlib
Predict time series data with neural network
Import of japandas with pandas 1.0 and above