【问题标题】:how to plot time series where x-axis is datetime.time object in matplotlib?如何在 matplotlib 中绘制 x 轴为 datetime.time 对象的时间序列?
【发布时间】:2016-02-09 06:16:52
【问题描述】:

我正在尝试绘制从晚上 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 轴上使用字符串标签的解决方案?

【问题讨论】:

    标签: python datetime numpy pandas matplotlib


    【解决方案1】:

    一种简单的方法是在不显式 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()
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-17
      • 1970-01-01
      • 2021-05-06
      • 2022-08-08
      • 1970-01-01
      • 2020-12-17
      • 2018-08-31
      相关资源
      最近更新 更多