在 python 中,使用 Seaborn 库,有什么方法可以将百分比刻度添加到我的图表值中吗?

in python, using Seaborn library, is there any way I can add percentage ticks to my graphs values?

我有一个包含二进制值和连续值的数据集,我创建了一个循环来使用 Seaborn 绘制它们,我想要一个百分比来说明每列的比例。有什么想法吗?

#lets set the visual palet and figure and grid size
sns.set_palette('Accent')
plt.figure(figsize=(15,18))
the_grid = GridSpec(5, 3)
#loop thrue the dataframs features and plot them, use countplot if they are binary and distplot if they are not binary
for i,column in enumerate(gym_churn.drop('churn', axis=1).columns):
    plt.subplot(the_grid[i//3, i%3], title=column.replace('_',' '))
    if gym_churn[column].unique().sum() == 1:
        sns.countplot(x=column, hue='churn', data=gym_churn)
        plt.xlabel('')
        plt.ylabel('')
        plt.gca().get_legend().remove()
        
        if column == 'near_location':
            legend = gym_churn['churn'].unique()
            plt.legend(legend, shadow=True, fancybox=True, title='churn', loc='best')
    if gym_churn[column].unique().sum() > 1:
        sns.distplot(gym_churn[gym_churn['churn'] == 0][column], hist = False, kde = True, kde_kws = {'bw' : 1})
        sns.distplot(gym_churn[gym_churn['churn'] == 1][column], hist = False, kde = True, kde_kws = {'bw' : 1})
        plt.xlabel('')
        plt.ylabel('')
    


plt.suptitle('Feature Distribution', fontsize = 14)
#plt.tight_layout()
plt.show()

您需要的功能是annotate。您可以使用此命令在绘图上写任何内容。 Deepak Natarajan 回答)有堆栈溢出回答,您可以在其中找到代码。在您的情况下,您需要函数 with_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()

在link上查看如何使用该功能,您需要先创建一个countplot