【问题标题】:How to plot data, time on x-axis not datetime如何绘制数据,x轴上的时间而不是日期时间
【发布时间】:2020-05-06 07:25:21
【问题描述】:
   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'] 是日期时间类型。

我该怎么办?谢谢。

【问题讨论】:

  • 尝试用df['timestamp'].dt.time替换df['timestamp']

标签: python pandas matplotlib data-visualization


【解决方案1】:

如果您的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'])

【讨论】:

  • 我已经尝试将日期时间转换为时间 df['timestamp'] = pd.to_datetime(df['timestamp]) df['time] = df['timestamp].dt.time 像这样.但是当我绘图时, TypeError : float() 参数必须是一个字符串或一个数字,即使我用你的答案代码进行了测试,也不会发生'datetime.time'。
  • 看起来matplotlib不允许“时间”类型,你可以尝试将df["time"]转换为string类型df["time"] = df["timestamp"].map(lambda x: x.strftime("%H:%M"))并尝试再次绘制plt.scatter(df['time'], df['energy'])
【解决方案2】:

首先检查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()

【讨论】:

  • df['timestamp'] 已经是日期时间类型。它仍然像第二张图一样绘制。
猜你喜欢
  • 1970-01-01
  • 2017-06-26
  • 2016-07-29
  • 2014-06-02
  • 1970-01-01
  • 2016-06-24
  • 2020-12-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多