由另一列组织的一列元素计数的堆积条

Stacked bars of counts of the elements of one column organised by another column

我很难制作一个图表,其中一个特征的计数按另一个特征堆叠。

假设数据帧如下:

     method  year proteins  values       QC
0      John  2018        A      30     PASS
1      Kate  2018        B      11     PASS
2      Kate  2018        C      22  NO-PASS
3   Patrick  2019        A      60     PASS
4   Patrick  2019        B      40  NO-PASS
5   Patrick  2019        C      50  NO-PASS
6      Mary  2017        A       8  NO-PASS
7      Mary  2017        B      11     PASS

到目前为止我有这个:(df['QC'].value_counts(dropna=True, normalize=True)*100).plot(kind='bar', rot=0, color='c', title='how many pass QC').set(xlabel="QC options", ylabel="% proteins")它生成一个基本的计数条形图。

但我实际上需要每个条形图 “由每种蛋白质的计数构建”,就像下面用 excel 制作的条形图一样。我也尝试过旋转它,但后来我没有数字数据,我无法从那里继续前进。

感谢您的帮助!

Pandas 将每列绘制为 bars 并使用关键字 stacked=True 堆叠它们。所以你必须计算和重塑你的数据以适应这个逻辑。

# Get the #'s data points in the groups
gdf = df.groupby(['proteins', 'QC'])['values'].count()

# Normalize to 100.0
gdf = gdf.div(gdf.sum())*100.0

# Since we want to stack by protiens, lets make them columns
gdf = gdf.unstack('proteins')

# If you want to choose a subset of columns to plot
col_to_plot = gdf.columns.tolist()

# Plot command
gdf[col_to_plot].plot(kind='bar', stacked=True)