Python:在条形图中绘制百分比

Pag*_*Max 2 python bar-chart pandas seaborn

对于数据框

import pandas as pd
df=pd.DataFrame({'group':list("AADABCBCCCD"),'Values':[1,0,1,0,1,0,0,1,0,1,0]})
Run Code Online (Sandbox Code Playgroud)

我试图绘制一个显示时间百分比A, B, C, D为零(或一个)的条形图。

我有一个可行的方法,但我认为必须有更直接的方法

tempdf=df.groupby(['group','Values']).Values.count().unstack().fillna(0)
tempdf['total']=df['group'].value_counts()
tempdf['percent']=tempdf[0]/tempdf['total']*100

tempdf.reset_index(inplace=True)
print tempdf

sns.barplot(x='group',y='percent',data=tempdf)
Run Code Online (Sandbox Code Playgroud)

如果仅绘制平均值,我可以sns.barplotdf数据框上比tempdf 做更多。如果我对绘制百分比感兴趣,我不确定如何优雅地做到这一点。

谢谢,

Ant*_*pov 8

您可以在 中使用自己的函数sns.barplot estimator,如文档所示

estimator:可调用的映射向量 -> 标量,可选的
统计函数以在每个分类箱内进行估计。

对于您的情况,您可以将函数定义为 lambda:

sns.barplot(x='group', y='Values', data=df, estimator=lambda x: sum(x==0)*100.0/len(x))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


小智 6

您可以按照以下步骤操作,以便可以在绘图中的条形顶部看到计数和百分比。检查下面的示例输出

如果绘图中有“hue”参数,则with_hue函数将在条形图上绘制百分比。它以实际的图、特征、特征中的Number_of_categories和hue_categories(色调特征中的类别数)作为参数。

如果您有正常的绘图, without_hue函数将在条形图上绘制百分比。它以实际的图形和特征作为参数。

def with_hue(plot, feature, Number_of_categories, hue_categories):
    a = [p.get_height() for p in plot.patches]
    patch = [p for p in plot.patches]
    for i in range(Number_of_categories):
        total = feature.value_counts().values[i]
        for j in range(hue_categories):
            percentage = '{:.1f}%'.format(100 * a[(j*Number_of_categories + i)]/total)
            x = patch[(j*Number_of_categories + i)].get_x() + patch[(j*Number_of_categories + i)].get_width() / 2 - 0.15
            y = patch[(j*Number_of_categories + i)].get_y() + patch[(j*Number_of_categories + i)].get_height() 
            ax.annotate(percentage, (x, y), size = 12)
    plt.show()

def without_hue(plot, feature):
    total = len(feature)
    for p in ax.patches:
        percentage = '{:.1f}%'.format(100 * p.get_height()/total)
        x = p.get_x() + p.get_width() / 2 - 0.05
        y = p.get_y() + p.get_height()
        ax.annotate(percentage, (x, y), size = 12)
    plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在此输入图像描述


mgo*_*ser 5

您可以将Pandas与seaborn结合使用,以使其更容易:

import pandas as pd
import seaborn as sns

df = sns.load_dataset("tips")
x, y, hue = "day", "proportion", "sex"
hue_order = ["Male", "Female"]

(df[x]
 .groupby(df[hue])
 .value_counts(normalize=True)
 .rename(y)
 .reset_index()
 .pipe((sns.barplot, "data"), x=x, y=y, hue=hue))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明