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.
pandas:0.24.2 matplotlib:3.1.0
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()
#Use pandas plot function
df.plot()
If the DataFrame index is DatetimeIndex, it will automatically format the tick. If this format is OK, that's fine.
import matplotlib.dates as mdates
#Use pandas plot function
ax = df.plot()
#Reformat
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m/%d'))
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
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'))
% 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.