我正在使用一个程序绘制一个Pandas 数据框,其中日期和时间在x轴上,变量在y轴上.我希望绘图以yyyy-mm-dd hh:mm格式显示x轴上每个刻度的日期和时间.
这是我正在使用的代码(我已经硬编码了一个简单的数据帧,使这段代码易于复制).下面的代码显示this figure,它具有我想要的日期和时间格式.
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib import dates as mdates
df = pd.DataFrame(
[['2022-01-01 01:01', 5],
['2022-01-01 07:01', 10],
['2022-01-01 13:01', 15],
['2022-01-01 19:01', 10]], columns=['Time', 'Variable'])
df['Time'] = pd.to_datetime(df['Time'])
df = df.set_index('Time')
fig, ax = plt.subplots()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
df.plot(ax=ax)
ax.tick_params(axis='x', labelrotation=45)
plt.show()
如果我从每个时间中减go 一分钟,然后运行下面的代码,我得到this figure,这是一个完全不同的日期和时间格式.
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib import dates as mdates
df = pd.DataFrame(
[['2022-01-01 01:00', 5],
['2022-01-01 07:00', 10],
['2022-01-01 13:00', 15],
['2022-01-01 19:00', 10]], columns=['Time', 'Variable'])
df['Time'] = pd.to_datetime(df['Time'])
df = df.set_index('Time')
fig, ax = plt.subplots()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
df.plot(ax=ax)
ax.tick_params(axis='x', labelrotation=45)
plt.show()
除了每次减go 一分钟外,我没有对代码进行任何更改,但记号的格式发生了变化,尽管我使用了set\u major\u formatter和set\u minor\u formatter方法来指定每个记号的格式.
有没有办法确保刻度的格式保持不变,而不管绘制的数据集是什么?