我想使用以下数据框创建水平条形图
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')
您能否告诉我如何使用原始数据框中的“类型”列创建相同的图表,将 q 数据分为 3 个子组(即学生、活跃和新生)?
最佳答案
您有三个选择。
使用 Pandas :
dfObj.groupby('Type')['q'].value_counts().plot(kind='barh')
使用 pandas 堆叠条:
dfObj.groupby('Type')['q'].value_counts().unstack(level=0).plot.barh(stacked=True)
使用 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')
关于python - 具有 2 列的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68892938/