首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在python中,使用Seaborn库,有任何方法可以在图形值中添加百分数吗?

在python中,使用Seaborn库,有任何方法可以在图形值中添加百分数吗?
EN

Stack Overflow用户
提问于 2021-01-02 16:11:44
回答 1查看 88关注 0票数 0

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

代码语言:javascript
复制
#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()

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-02 17:52:48

您需要的函数是annotate。您可以使用以下命令在绘图上编写任何内容。Here (Deepak 应答)有堆栈溢出应答,您可以在那里找到代码。在您的例子中,您需要函数with_hue。谨随函附上:

代码语言:javascript
复制
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()

在链接上,检查如何使用该函数,您需要首先创建一个countplot

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65541268

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档