簡體   English   中英

Plot 元素在同一圖表上的 dataframe 的列中,以日期時間格式共享相同的 x 軸

[英]Plot elements in a column of a dataframe on the same graph sharing the same x-axis in datetime format

我有一個 dataframe:


    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

我想要 plot 值“元素”列中的兩個元素的值“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')

圖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()

圖2

我想用一個共同的日期范圍來表示共享 x 軸的兩組點,我需要一個帶有標簽“A”和“B”的圖例。

如果您將Date列轉換為 Timestamp,您的第一次嘗試就會失敗。 散點圖 plot 要求 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")

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM