【问题标题】:Matplotlib not reading time axis correctlyMatplotlib 未正确读取时间轴
【发布时间】:2020-05-19 20:51:24
【问题描述】:

我想使用Matplotlib 可视化每日数据。数据是温度与时间的关系,格式如下:

    Time    Temperature

1   8:23:04      18.5
2   8:23:04      19.0
3   9:12:57      19.0
4   9:12:57      20.0
... ... ...

但是在绘制图形时,x-axis 上的 Time 值会失真,如下所示:

意识到Matplotlib 可能无法正确解释时间数据,我使用pd.to_datetime 转换了时间格式:

df['Time'] = pd.to_datetime(df['Time'], format="%H:%M:%S")  

df.plot( 'Time', 'Temperature',figsize=(20, 10))

df.describe()

但这又返回了:

如何让x-axis上的时间看起来正常?谢谢

【问题讨论】:

  • df.dtypes 的输出是什么?
  • @MichaelO.Time:object; Temperature: float64; dtype: object
  • 是什么给了df.iloc[0, 0]
  • @MichaelO。它返回了'17:29:33'
  • 所以Time 的格式错误,因为它应该返回类似Timestamp('1900-01-01 08:23:04') 的内容。此外,由于您有 17 小时和 08 小时的时间,看起来您的时间列包含超过一天,因此您应该将年、月和日添加到数据中。

标签: python pandas numpy matplotlib time


【解决方案1】:

正如@Michael O. 所说,您需要注意日期时间。 你错过了日、年和月。在这里,我实现了一个可能的解决方案,将这些缺失的数据添加到一些默认值中,您可能想要更改它们。 代码非常简单,cmets 说明了我在做什么。

import pandas as pd
from datetime import datetime, date, time, timezone
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

vals=[["8:23:04",      18.5],
["8:23:04",      19.0],
["9:12:57",      19.0],
["9:12:57",      20.0]]
apd=pd.DataFrame(vals, columns=["Time", "Temp"])

# a simple function to convert a string to datetime
def conv_time(cell):
    dt = datetime.strptime(cell, "%d/%m/%Y %H:%M:%S")
    return(dt)


# the dataframe misses the day, month and year, we need to add some
apd["Time"]=["{}/{}/{} {}".format(1,1,2020, cell) for cell in apd["Time"]]

# we use the function to convert the column to a datetime
apd["Time"]=[conv_time(cell) for cell in apd["Time"]]

## plotting the results taking care of the axis
fig, ax = plt.subplots()
ax.xaxis.set_major_formatter(mdates.DateFormatter("%H"))
ax.set_xlim([pd.to_datetime('2020-01-1 6:00:00'), pd.to_datetime('2020-01-1 12:00:00')])
ax.scatter(apd["Time"], apd["Temp"])

【讨论】:

  • 您好,感谢您的回答。是否可以显示图表的“time”数据?因为我对时间比对日期更感兴趣。非常感谢!
  • 我做了一些更改,但我不太明白您的评论。如果这是您想要的,我会以小时为单位更改轴。
  • 是的。我正是这个意思。我认为它现在正在工作。谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-09
  • 1970-01-01
  • 2019-06-01
相关资源
最近更新 更多