简体   繁体   English

如何 plot 数据,x 轴上的时间不是日期时间

[英]How to plot data, time on x-axis not datetime

   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

I want to plot these data like below.我想 plot 这些数据如下所示。 just time on x-axis, not date nor datetime.只是 x 轴上的时间,而不是日期或日期时间。

because I want to see the values per each hour.因为我想查看每小时的值。

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

but this code plot like this.但是这个代码 plot 就像这样。

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

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

I tried some codes but they just format the X data hide date part and plot like second graph.我尝试了一些代码,但它们只是格式化 X 数据隐藏日期部分和 plot 就像第二张图一样。

+ df['timestamp'] is datetime type. + df['timestamp'] 是日期时间类型。

what should I do?我应该怎么办? Thanks.谢谢。

you can convert your datetime into time, if your df["timestamp"] is already in datetime format then您可以将您的日期时间转换为时间,如果您的df["timestamp"]已经是日期时间格式,那么

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

if df["timestamp"] is of type string then you can add one more line in front as df["timestamp"] = pd.to_datetime(df["timestamp"])如果df["timestamp"]是字符串类型,那么您可以在前面再添加一行df["timestamp"] = pd.to_datetime(df["timestamp"])

Update: look like matplotlib does not accept time types, just convert to string更新:看起来 matplotlib 不接受time类型,只需转换为string

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

First check, if type of df["timestamp"] is in datetime format.首先检查df["timestamp"]的类型是否为日期时间格式。 if not如果不

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

Then,然后,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM