首页 > 解决方案 > matplotlib plot 更改 datetime64 的日期顺序

问题描述

我正在努力绘制我的数据。

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 200 entries, 0 to 200
Data columns (total 3 columns):
DateTime     200 non-null datetime64[ns]
Y            200 non-null float64
YHAT         200 non-null float64
dtypes: datetime64[ns](1), float64(2)

东风:

Datetime            Y       YHAT        
2019-05-11 11:00:00 9.513   11.656448
2019-05-11 12:00:00 11.262  11.575493
2019-05-11 13:00:00 11.604  11.730906
2019-05-11 14:00:00 10.423  11.898123
2019-05-11 15:00:00 12.617  12.403809
2019-05-11 16:00:00 12.185  12.600061
2019-05-11 17:00:00 14.256  12.525238
2019-05-11 18:00:00 14.276  12.127124
2019-05-11 19:00:00 11.296  11.513634
2019-05-11 20:00:00 11.198  11.547970
2019-05-11 21:00:00 14.787  12.274036
2019-05-11 22:00:00 11.209  13.037806
2019-05-11 23:00:00 11.202  14.049373
2019-06-11 00:00:00 6.305   14.444961
2019-06-11 01:00:00 8.901   14.425690
2019-06-11 02:00:00 9.130   14.676990
2019-06-11 03:00:00 8.784   14.725097
2019-06-11 04:00:00 8.931   14.841638
2019-06-11 05:00:00 10.358  14.956691
2019-06-11 06:00:00 9.024   15.077591

这是绘图功能:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

plt.plot(df.Datetime, df.y, label="Y")
plt.plot(df.Datetime, df.yhat, label="YHAT")
plt.legend()
fig = plt.gcf()
fig.set_size_inches(15,5)
axes = fig.axes[0]
xfmt = mdates.DateFormatter("%y-%d-%m %H:%M")
axes.xaxis.set_major_formatter(xfmt)
plt.show()

这是输出:

在此处输入图像描述

输出完全混乱。似乎日期时间不是连续的,尽管在我的数据集中我的数据按Datetime.

标签: pythonpandasmatplotlib

解决方案


看起来您df自己推断出的Datetime列格式错误(年-月-日而不是年-日-月)。因此,当您的mdates格式化程序要求时%m-%d,它会提取错误的值(并且不知道)。

如果我明确转换df.Datetimeformat='%Y-%d-%m %H:%M:%S'

df = pd.read_csv('data.csv')
df.Datetime = pd.to_datetime(df.Datetime, format='%Y-%d-%m %H:%M:%S')

然后输出如预期:

fig, ax = plt.subplots(figsize=(15,5))
ax.plot(df.Datetime, df.y, label='Y')
ax.plot(df.Datetime, df.yhat, label='YHAT')
ax.legend()
xfmt = mdates.DateFormatter('%Y-%m-%d %H:%M')
ax.xaxis.set_major_formatter(xfmt)

更正日期格式后的数字输出


推荐阅读