gpt4 book ai didi

python - 带 2 列的条形图

转载 作者:行者123 更新时间:2023-12-04 07:14:05 25 4
gpt4 key购买 nike

我想使用以下数据框创建水平条形图

studentData = { 
0 : {
'stylevel' : 'bachelor',
'q' : 'agree',
'Type' : 'Nascent'
},
1 : {
'stylevel' : 'bachelor',
'q' : 'very',
'Type' : 'Nascent'
},
2 : {
'stylevel' : 'master',
'q' : 'very',
'Type' : 'Active'
},
3 : {
'stylevel' : 'master',
'q' : 'agree',
'Type' : 'Active'
},
4 : {
'stylevel' : 'master',
'q' : 'agree',
'Type' : 'Student'
},
}

dfObj = pd.DataFrame(studentData)
dfObj = dfObj.T
我正在使用以下代码绘制图形
dfObj['q'].value_counts().plot(kind='barh')
您能告诉我如何使用原始数据框中的 Type 列创建相同的图形以将 q 数据分成 3 个子组(即学生、事件和新生)吗?

最佳答案

你有三个选择。
使用 Pandas :

dfObj.groupby('Type')['q'].value_counts().plot(kind='barh')
pandas bar plot
使用 Pandas 堆叠条:
dfObj.groupby('Type')['q'].value_counts().unstack(level=0).plot.barh(stacked=True)
pandas stacked bars
使用 seaborn.catplot :
import seaborn as sns
df2 = dfObj.groupby('Type')['q'].value_counts().rename('count').reset_index()
sns.catplot(data=df2, x='q', hue='Type', y='count', kind='bar')
seaborn catplot

关于python - 带 2 列的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68892938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com