具有特定数据结构的百分比堆积条形图 [英] Percentage stacked bar chart with a specific data structure

查看:79
本文介绍了具有特定数据结构的百分比堆积条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下特定的数据结构:

I have the following specific data structure:

df = pd.DataFrame(columns=["Feature1", "Target"], 
                  data=[["A", 0],
                        ["A", 0],
                        ["A", 0],
                        ["A", 1],
                        ["A", 1],
                        ["A", 1], 
                        
                        ["B", 1],
                        ["B", 1],
                        ["B", 0],
                        ["B", 0],
                        ["B", 0]])

如何绘制如下所示的百分比堆积条形图,以便显示两组 A 和 B 中 0 和 1 的比例?

How do I plot a percentage stacked bar chart which looks something like the below, so that I can show the proportions of 0's and 1's in the two groups A and B?

注意:dataframe df 中的比例与图片中显示的不同.

Note: the proportions in the dataframe df are different to the ones shown in the picture.

推荐答案

您可以先计算每种类型的值,然后除以每种功能的总和再乘以100.

You could first count the values of each type, then divide by the total for each feature and multiply by 100.

结果数据框可以绘制如下:

The resulting dataframe can be plotted as follows:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

sns.set()
df = pd.DataFrame(columns=["Feature1", "Target"],
                  data=[["A", 0], ["A", 0], ["A", 0], ["A", 1], ["A", 1], ["A", 1],
                        ["B", 1], ["B", 1], ["B", 0], ["B", 0], ["B", 0]])
df1 = (df.groupby(["Feature1", "Target"]).size() / df.groupby(["Feature1"]).size() * 100)
df1 = df1.reset_index(name='Percentage')
features = np.unique(df1['Feature1'])
plt.bar(x=features, height=100, color='dodgerblue', label='Target = 1')
plt.bar(x=features,
        height=[df1[(df1['Feature1'] == x) & (df1['Target'] == 0)]['Percentage'].values[0] for x in features],
        color='crimson', label='Target = 0')
plt.legend()
plt.xlabel('Feature1')
plt.ylabel('Percentage')
plt.show()

这篇关于具有特定数据结构的百分比堆积条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆