【问题标题】:Matplotlib: Timestamp not appearing on x-axisMatplotlib:时间戳未出现在 x 轴上
【发布时间】:2019-06-01 21:38:05
【问题描述】:

我想显示 24 小时内每小时的平均“流量”(数周内每分钟收集一次数据)。我当前的代码不会产生 x 轴上的时间戳。我不清楚为什么会这样。

数据集如下所示:

时间_______流___maneuver_____时间_c

15420226756.751___0.0__________1_______12:45:56

15420227756.761__ 0.1__________2_______13:45:56

15420228756.771___0.2__________3_______14:40:30

15420229756.781___0.5__________1_______15:30:20

15420230756.791___0.6______________2_______15:57:00

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

flow_1810['time_c'] = pd.to_datetime(flow_1810['time'],unit='s').apply(lambda x: str(str(x).split(' ')[1]).split('.')[0])

fig, ax = plt.subplots(figsize=(15,7))
flow_1810.groupby(['time_c','maneuver']).median()['flow'].unstack().plot(ax=ax)

# beautify the x-labels
plt.gcf().autofmt_xdate()
myFmt = mdates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(myFmt)
ax.xaxis.set_major_locator(mdates.HourLocator(byhour=range(0,24,3)))

这是结果:

这是时间戳的格式:(int64)

【问题讨论】:

  • 什么是mdates?我怀疑这是日期格式的问题。您能否制作一个最小、完整且可验证的示例 (stackoverflow.com/help/mcve),因为它可以帮助人们回答。
  • @EdSmith,我已经更新了我的问题。
  • 嘿 sos.cott,你能分享示例文件或原件来执行此操作吗?
  • @AmitAmola,当然,这是一个谷歌表格链接:docs.google.com/spreadsheets/d/…
  • 您能告诉我您的日期时间值以哪种格式保存在文件中吗?在不知道时间格式的情况下,我无法进行日期时间转换。

标签: python matplotlib plot timestamp axis-labels


【解决方案1】:

试试这个:

import pandas as pd
from datetime import datetime

df=pd.read_csv('newdata2.csv')
df.time=df.time.apply(lambda x:x.replace(',',''))
df['time_c'] = df['time'].apply(lambda x:datetime.utcfromtimestamp(float(x)).strftime('%Y-%m-%d-%H'))
df.time_c=pd.to_datetime(df.time_c, format='%Y-%m-%d-%H')

df.groupby(by=['time_c']).flow.sum().plot(figsize=(14,8))

让我知道它是否有效。

【讨论】:

  • 这个例子只返回日期而不是小时。
  • 它附有小时 sos.cott。这是一个日期时间类型的索引。您是否通过上述代码绘制了您的值?
猜你喜欢
  • 2019-07-25
  • 2015-05-02
  • 2019-04-17
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多