【问题标题】:Plot elements in a column of a dataframe on the same graph sharing the same x-axis in datetime format在同一个图形上以日期时间格式共享相同 x 轴的数据框列中绘制元素
【发布时间】:2022-11-30 08:00:31
【问题描述】:

我有一个数据框:


    Element Date                Q

0   A       24/10/2021 17:16    400
1   B       24/10/2021 18:59    210
2   A       26/10/2021 18:42    325
3   A       26/10/2021 19:44    589
4   B       29/10/2021 14:23    251
5   A       01/11/2021 9:12     578
6   B       02/11/2021 21:30    321
7   A       04/11/2021 18:25    248
8   B       05/11/2021 10:29    854
9   A       05/11/2021 10:26    968
10  A       07/11/2021 18:10    852
11  A       09/11/2021 16:35    425
12  B       09/11/2021 21:55    752
13  A       11/11/2021 18:41    385
14  B       13/11/2021 11:15    658
15  A       14/11/2021 18:17    229
16  B       16/11/2021 22:36    258
17  A       17/11/2021 17:05    359
18  A       18/11/2021 16:39    210
19  B       19/11/2021 15:41    583

我想在同一个图表中绘制“元素”列中两个元素的值“Q”,共享相同的 x 轴,但我无法得到它。

我试图将它们分成两个数据框,但这不是一个好的解决方案:

    Element Date                Q
0   A       24/10/2021 17:16    400
2   A       26/10/2021 18:42    325
3   A       26/10/2021 19:44    589
5   A       01/11/2021 9:12     578
7   A       04/11/2021 18:25    248
9   A       05/11/2021 10:26    968
10  A       07/11/2021 18:10    852
11  A       09/11/2021 16:35    425
13  A       11/11/2021 18:41    385
15  A       14/11/2021 18:17    229
17  A       17/11/2021 17:05    359
18  A       18/11/2021 16:39    210
    Element Date                Q
1   B       24/10/2021 18:59    210
4   B       29/10/2021 14:23    251
6   B       02/11/2021 21:30    321
8   B       05/11/2021 10:29    854
12  B       09/11/2021 21:55    752
14  B       13/11/2021 11:15    658
16  B       16/11/2021 22:36    258
19  B       19/11/2021 15:41    583

这是两次尝试的结果:

ax = dfA.plot.scatter(x="Date",y="Q",rot=90)
dfB.plot.scatter(x="Date",y="Q",rot=90, ax=ax, color='r')

Graph 1

df_A = df[df['Element'] == 'A'].set_index('Date')
df_B = df[df['Element'] == 'B'].set_index('Date')

plt.figure()

ax = df_A[['Q']].plot(figsize=(20,5))
df_B[['Q']].plot(ax=ax)
ax.xaxis.set_major_locator(mdates.DayLocator(interval=1))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))

plt.gcf().autofmt_xdate()
plt.show()

Graph 2

我想用一个共同的日期范围来表示共享 x 轴的两组点,我需要一个带有标签“A”和“B”的图例。

【问题讨论】:

    标签: python pandas datetime plot x-axis


    【解决方案1】:

    如果您将 Date 列转换为 Timestamp,您的第一次尝试就会失败。散点图要求 x 轴和 y 轴上的值均为数值。当您在 x 轴上提供字符串时,它们将被视为位置 [0, 1, 2, 3,...]刻度线等于提供的值。

    for df in [dfA, dfB]:
        df["Date"] = pd.to_datetime(df["Date"], dayfirst=True)
    
    ax = dfA.plot.scatter(x="Date", y="Q", rot=90, label="A")
    dfB.plot.scatter(x="Date", y="Q", rot=90, ax=ax, color="r", label="B")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-03
      • 2019-08-31
      • 2020-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多