python - 如何绘制时间序列,其中 x 轴是 matplotlib 中的 datetime.time 对象?

标签 python datetime numpy pandas matplotlib

我正在尝试绘制从晚上 9 点到第二天下午 6 点的时间序列数据图表。这是我失败的尝试。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import time    

a=np.array([35,25,24,25,27,28,30,35])
df=pd.DataFrame(index=pd.date_range("00:00", "23:00", freq="3H").time,data={'column1':a})

          column1
00:00:00       35
03:00:00       25
06:00:00       24
09:00:00       25
12:00:00       27
15:00:00       28
18:00:00       30
21:00:00       35

重新索引数据从 21:00 到 18:00。也许也有更好的方法来实现这一部分,但这行得通。

df=df.reindex(np.concatenate([df.loc[time(21,00):].index,df.loc[:time(21,00)].index[:-1]]))

          column1
21:00:00       35
00:00:00       35
03:00:00       25
06:00:00       24
09:00:00       25
12:00:00       27
15:00:00       28
18:00:00       30

plt.plot(df.index,df['column1'])

x 轴似乎与 df.index 不匹配。轴也从 00:00 开始,而不是 21:00。有谁知道不涉及对 x 轴使用字符串标签的解决方案?

最佳答案

一个简单的方法是在不显式 x 轴和更改标签的情况下绘制数据。问题是这只有在数据之间的时间是恒定的情况下才有效。我知道你说过你不想使用字符串标签,所以我不知道这个解决方案会是你想要的。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import time    

a=np.array([35,25,24,25,27,28,30,35])

df=pd.DataFrame(index=pd.date_range("00:00", "23:00",freq="3H").time,data={'column1':a})

df=df.reindex(np.concatenate([df.loc[time(21,00):].index,df.loc[:time(21,00)].index[:-1]]))

# Now we create the figure and the axes
fig,axes=plt.subplots()
axes.plot(df['column1'])  # In the x axis will appear 0,1,2,3...
axes.set_xticklabels(df.index)  # now we change the labels of the xaxis

plt.show()

这应该可以解决问题并绘制您想要的内容。

example of result

关于python - 如何绘制时间序列,其中 x 轴是 matplotlib 中的 datetime.time 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33594942/

相关文章:

ruby-on-rails - Rails Postgre 日期时间保存为零

python - 属性错误 : Cannot access callable attribute 'groupby' of 'DataFrameGroupBy' objects

python - 子图中的 matplotlib 颜色条 : labels are vanishing

python - 终端中python中的Window OpenCV

php - 使用 'now()' 格式化存储在数据库中的时间

python - 在 Python 中解码一列 Base64 字符串

python - 如何在 matplotlib 中创建非线性颜色条刻度

python - 将 QdateTime 转换为普通的 python dateTime?

python - 为什么 numpy 数组有 96 字节的开销?

python - 从 1 维位数组中获取特定的 2 维序列数组 [Python]