簡體   English   中英

繪制兩列 dataframe 列,第三列作為 x 軸

[英]Plotting two dataframe columns with the third as x axis

我有以下 dataframe:

    type_of_thing  group1      group 2
0        type1     0.030659    0.052632
1        type2     0.099169    0.026316
2        type3     0.184580    0.236842
3        type4     0.469446    0.605263

我想要做的是比較第一組和第二組的每種類型。我想要的圖表有點像這樣: 在此處輸入圖像描述 (在 excel 中快速制作,但我正在生成我在腳本中使用的 dataframe)

我的代碼是這樣的:

import seaborn as sns
...
rest of code
...
sns.catplot(x='type_of_thing', y=group1,kind="bar", data=df)

或者我有這個代碼:

df.plot(kind='bar')
plt.show()

但是這樣顯示,當我希望 type_of_thing 列用作 x 軸的標簽時,完全忽略 type_of_thing 列: 在此處輸入圖像描述

有誰知道我如何修復這些代碼中的一個或兩個以獲得我想要的結果?

您可能需要熔化您的 dataframe 以使其形狀正確,然后您應該能夠將group用作您的 x,並將type_of_thing用作您的色調

import pandas as pd
import seaborn as sns
df = pd.DataFrame({'type_of_thing': ['type1', 'type2', 'type3', 'type4'],
 'group1': [0.030659, 0.09916900000000001, 0.18458, 0.46944600000000003],
 'group2': [0.052632000000000005, 0.026316000000000003, 0.236842, 0.605263]})


df = df.melt(id_vars='type_of_thing', var_name='group')
# So you can see what happened with melt and why it helps here
print(df)

sns.catplot(data=df, x='group',y='value', kind='bar', hue='type_of_thing')

這是融化的 df 的樣子:

  type_of_thing   group     value
0         type1  group1  0.030659
1         type2  group1  0.099169
2         type3  group1  0.184580
3         type4  group1  0.469446
4         type1  group2  0.052632
5         type2  group2  0.026316
6         type3  group2  0.236842
7         type4  group2  0.605263

Output

在此處輸入圖像描述

暫無
暫無

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

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