如何在Seaborn Barplot中添加数据标签? [英] How to add data labels to seaborn barplot?

查看:33
本文介绍了如何在Seaborn Barplot中添加数据标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码可以在 seaborn 中生成条形图

I have the following code to produce a bar plot in seaborn

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

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
print(df):
    A   B   C   D
0   15  21  13   5
1   14  94  99  14
2   11  11  13  69
3   27  90  37   6
4   51  93  92  24
..  ..  ..  ..  ..
95  45  40  85  62
96  44  48  61  43
97  39  66  72  72
98  51  97  17  32
99  51  42  29  15


probbins = [0,10,20,30,40,50,60,70,80,90,100]
df['Groups'] = pd.cut(df['D'],bins=probbins)
plt.figure(figsize=(15,6))
chart = sns.barplot(x=df['Groups'], y=df['C'],estimator=sum,ci=None)
chart.set_title('Profit/Loss')
chart.set_xticklabels(chart.get_xticklabels(), rotation=30)
plt.show()

哪个给我:

如何简单地向该绘图添加数据标签?任何帮助将不胜感激!

How can I simply add data labels to this plot? Any help would be much appreciated!

推荐答案

对于那些对我的解决方法感兴趣的人:

For those intersted in how I solved it:

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

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
print(df):
    A   B   C   D
0   31  11  65  15
1   83  21   5  87
2   16   6  81  41
3   91  78  95  70
4   26  51  26  61
..  ..  ..  ..  ..
95  31  18  91  24
96  73  97  42  45
97  76  22   2  36
98  12  43  98  27
99  33  96  67  68


probbins = [0,10,20,30,40,50,60,70,80,90,100]
df['Groups'] = pd.cut(df['D'],bins=probbins)
plt.figure(figsize=(15,6))
chart = sns.barplot(x=df['Groups'], y=df['C'],estimator=sum,ci=None)
chart.set_title('Profit/Loss')
chart.set_xticklabels(chart.get_xticklabels(), rotation=30)
# annotation here
for p in chart.patches:
             chart.annotate("%.0f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()),
                 ha='center', va='center', fontsize=10, color='black', xytext=(0, 5),
                 textcoords='offset points')
plt.show()

这篇关于如何在Seaborn Barplot中添加数据标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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