python - 具有 2 列的条形图

标签 python pandas matplotlib

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

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 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/

相关文章:

python - 带有 Gunicorn Dockerized 的 Flask 应用程序,监听 : http://0. 0.0.0 :8000, 但 URL 没有响应

python - 从 pandas 数据帧生成命名元组的字典

Python Pandas 数据框操作以形成更大的数据框

Python 正则表达式读取/etc/resolv.conf 并只返回 ip 地址,认为它几乎在那里,

python - 如何从 QtGui.QListWidget 获取当前 Item 的信息?

python - 尽管 xticks 有值(value),如何使它们均匀分布?

python - 在 Matplotlib 中填充 x 和基线 x 位置

python - 将大型数据框拆分为较小的 Pandas 数据框列表

python - 遍历 pandas 中的行并计算唯一的主题标签

python - 'datalim' 属性有什么作用?