python - 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
.
解决方案
看起来您df
自己推断出的Datetime
列格式错误(年-月-日而不是年-日-月)。因此,当您的mdates
格式化程序要求时%m-%d
,它会提取错误的值(并且不知道)。
如果我明确转换df.Datetime
为format='%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)
推荐阅读
- c++ - GRPC/C++ - 服务器只从双向流中读取第一条消息
- python - Get value from a line intersecting 0.0 level
- node.js - 错误离子服务确实弹出未处理的异常:NGCC失败
- c# - 如何从格式不同的字符串中提取数字?
- c# - 检查网格中瓷砖的相邻性
- c# - Web 服务器上的 HRESULT 0x80070057 - asp.net
- mysql - 为什么我在使用 AES_DECRYPT 时收到没有更多详细信息的错误?
- python - 使用 nltk 从字典中删除非英语单词
- c# - WPF 绑定问题 - 显示不可见的项目
- c - 为什么即使保证返回,我也会收到警告“控制到达非无效函数的结尾”