如何绘制数据,x轴上的时间而不是日期时间

时间:2020-05-06 07:25:21

标签: python pandas matplotlib data-visualization

   id        timestamp          energy
0   a   2012-03-18 10:00:00     0.034
1   b   2012-03-20 10:30:00     0.052
2   c   2013-05-29 11:00:00     0.055
3   d   2014-06-20 01:00:00     0.028
4   a   2015-02-10 12:00:00     0.069

我想绘制这些数据,如下所示。 只是沿x轴的时间,而不是日期或日期时间。

因为我想查看每小时的值。

https://i.stack.imgur.com/u73eJ.png

但是这段代码是这样的。

plt.plot(df['timestamp'], df['energy'])

https://i.stack.imgur.com/yd6NL.png

我尝试了一些代码,但是它们只是格式化X数据隐藏日期部分并像第二张图一样绘制。

+ df ['timestamp']是日期时间类型。

我该怎么办?谢谢。

2 个答案:

答案 0 :(得分:0)

如果您的df["timestamp"]已经是日期时间格式,则可以将日期时间转换为时间

df["time"] = df["timestamp"].map(lambda x: x.time())
plt.plot(df['time'], df['energy'])

如果df["timestamp"]是字符串类型,则可以在前面再添加一行df["timestamp"] = pd.to_datetime(df["timestamp"])

更新:看起来matplotlib不接受time类型,只是转换为string

df["time"] = df["timestamp"].map(lambda x: x.strftime("%H:%M"))
plt.scatter(df['time'], df['energy'])

答案 1 :(得分:0)

首先检查df["timestamp"]的类型是否为日期时间格式。 如果没有

import pandas as pd  
time = pd.to_datetime(df["timestamp"])
print(type(time))

然后

import matplotlib.pyplot as plt
values = df['energy']
plt.plot_date(dates , values )
plt.xticks(rotation=45)
plt.show()