【问题标题】:How to plot multiple timeseries data with different start date on the same x-axis in Python Matplotlib?如何在 Python Matplotlib 中的同一 x 轴上绘制具有不同开始日期的多个时间序列数据?
【发布时间】:2021-07-16 07:21:02
【问题描述】:

我正在尝试在同一个 x 轴上绘制三个具有不同开始日期的时间序列数据集,类似于这个问题 How to plot timeseries with different start date on the same x axis。除了我的 x 轴有日期而不是天数。

我的数据框结构如下:

日期 ColA 标签
01/01/2019 1.0 培训
02/01/2019 1.0 培训
...
14/09/2020 2.0 测试1
..
06/01/2021 4.0 测试2
...

我将每个时间序列定义为:

train = df.loc['01/01/2019':'05/08/2020', 'ColA']  
test1 = df.loc['14/09/2020':'20/12/2020', 'ColA']  
test2 = df.loc['06/01/2021':'18/03/2021', 'ColA']  

这是单个时间序列的绘图方式:

但是当我尝试将它们绘制在同一个 x 轴上时,它不会按日期顺序绘制 我希望产生这样的东西(来自 MS Excel):

任何帮助都会很棒!

谢谢

【问题讨论】:

  • 您想要 1 个带有连续的 train、test#1 和 test#2 的地块,还是想要多个地块?
  • 1 个情节,如我编辑的问题中所示。谢谢
  • 我已经修改了我的答案,希望对@BRat有帮助

标签: python pandas matplotlib time-series


【解决方案1】:

确保数据框中的“日期”列作为日期时间变量而不是字符串导入。

如果您发现 dtype 为“对象”:

df = pd.read_csv('data.csv')
data['Date']
0      2019-01-01
1      2019-01-02
2      2019-01-03
       

    Name: Date, Length: 830, dtype: object

您需要转换为日期时间变量。您可以通过两种方式进行转换:

  1. df = pd.read_csv('data.csv', parse_dates=['Date'])
    

  1. df = pd.read_csv('data.csv')
    df['Date'] = pd.to_datetime(data['Date'])
    

这两个选项都会给你同样的结果。

df = pd.read_csv('data.csv', parse_dates=['Date'])
data['Date']
0      2019-01-01
1      2019-01-02
2      2019-01-03
       ...

    Name: Date, Length: 830, dtype: datetime64[ns]

然后,您可以绘制:

plt.plot(data['Date'],ColA)

当您定义单个时间序列时,请务必检查日期格式。 pandas 中的日期时间格式为 YYYY-MM-DD。所以,改用这个:

train = df.loc['2019-01-01':'2020-08-05', 'ColA'] and so on...

我假设您的数据存储为 csv(或 excel)。如果是这样,当您在 Excel 中打开数据文件时,请注意 MS Excel 如何更改日期列的格式。 最佳做法是始终使用

检查“日期”列的格式
type(data['Date']) after importing dataframe.

【讨论】:

    【解决方案2】:

    我假设您的数据框至少包含训练、测试#1 和测试#2 的daterecordlabel
    sharex = True 会成功吗?

    fig, ax = plt.subplots(3,1, sharex = True)
    
    for i,j in zip(data['label'].unique(), range(3)):
        ax[j].plot(x = df[df['label'] == i]['date'], 
                   y = df[df['label'] == i]['record'])
    

    编辑

    应该这样做

    fig, ax = plt.subplots(figsize = (14,6))
    color = ['blue','red','orange']
    
    for i,j in zip(df.Label.unique().tolist(), color):
        ax.plot(x = df['Date'][df.Label == i], y = df['ColA'][df.Label == i], 
                color = j, label = j)
    plt.legend(loc = 'best')
    plt.show()
    

    你基本上想在 matplotlib 的同一个图中多次绘制。只需使用初始数据集(包括所有标签),无需使用单独的数据集。

    【讨论】:

    • 感谢您的回复。我不太喜欢你的解决方案。我的数据框结构如下:Date ColA Label 01/01/2019 1.0 Training 02/01/2019 1.0 Training ... 14/09/2020 2.0 Test1 .. 06/01/2021 4.0 Test2 ...我已经定义了每个时间序列为:train = df.loc['01/01/2019':'05/08/2020', 'ColA'] test1 = df.loc['14/09/2020':'20/12/2020 ', 'ColA'] test2 = df.loc['06/01/2021':'18/03/2021', 'ColA'] 如何在这里应用你的'for'循环?在此先感谢:-)
    • 我收到 KeyError: 'Date'
    • 我使用了date 而不是Date(大写D),您尝试过更改吗?
    • 是的。 “日期”和“日期”都出现同样的错误
    • 尝试使用ax.plot_date 而不是ax.plot 进行绘图。该错误可能是因为您的数据采用datetime 格式
    猜你喜欢
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 2020-12-31
    • 2020-07-02
    • 2019-08-31
    相关资源
    最近更新 更多