我正在使用一个程序绘制一个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方法来指定每个记号的格式.

有没有办法确保刻度的格式保持不变,而不管绘制的数据集是什么?

推荐答案

下面的代码通过避免默认值来回避这个问题.

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'])
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'))
ax.plot('Time','Variable',data=df)
ax.tick_params(axis='x', labelrotation=45)

Python相关问答推荐

如何计算列表列行之间的公共元素

多处理代码在while循环中不工作

PywinAuto在Windows 11上引发了Memory错误,但在Windows 10上未引发

如何删除索引过go 的lexsort深度可能会影响性能?' &>

未删除映射表的行

无法使用DBFS File API路径附加到CSV In Datricks(OSError Errno 95操作不支持)

Pandas计数符合某些条件的特定列的数量

将JSON对象转换为Dataframe

实现神经网络代码时的TypeError

Plotly Dash Creating Interactive Graph下拉列表

考虑到同一天和前2天的前2个数值,如何估算电力时间序列数据中的缺失值?

为什么'if x is None:pass'比'x is None'单独使用更快?

具有相同图例 colored颜色 和标签的堆叠子图

Python—为什么我的代码返回一个TypeError

freq = inject在pandas中做了什么?''它与freq = D有什么不同?''

如何在Airflow执行日期中保留日期并将时间转换为00:00

当HTTP 201响应包含 Big Data 的POST请求时,应该是什么?  

用来自另一个数据框的列特定标量划分Polars数据框中的每一列,

利用SCIPY沿第一轴对数组进行内插

为什么我只用exec()函数运行了一次文件,而Python却运行了两次?