繁体   English   中英

python 条形图总 label 条形图

[英]python bar chart total label on bar

plt.figure(figsize = (8,5))
sns.countplot(data = HRdfMerged, x = 'Gender', hue='Attrition').set_title('Gender vs Attrition')

我很难在我的栏顶部添加一个 label 来说明总数。 我尝试了许多不同的方法,但无法做到正确。 我正在使用 matplotlib。 添加了条形图的图片。

条形图图像

调用sns.countplot ,我们将探索列表ax.patches以从条形图中获取信息并放置所需的文本:

在此处输入图像描述


# Imports.
import matplotlib.pyplot as plt
import seaborn as sns

# Load a dataset and replicate what you have in the question, since you did
# not provide any data to help us help you. 
data = sns.load_dataset("titanic")
fig, ax = plt.subplots() # Use the object-oriented approach with Matplotlib when you can.
sns.countplot(data=data, x="class", hue="who", ax=ax)
ax.set_title("title goes here")
fig.show()

# For each bar, grab its coordinates and colors, find a suitable location
# for a text and place it there.
for patch in ax.patches:
    x0, y0 = patch.get_xy()   # Bottom-left corner. 
    x0 += patch.get_width()/2 # Middle of the width.
    y0 += patch.get_height()  # Top of the bar
    color = patch.get_facecolor()
    ax.text(x0, y0, str(y0), ha="center", va="bottom", color="white", clip_on=True, bbox=dict(ec="black",
                                                                                              fc=color))

使用ax.text的 kwargs 来获得您喜欢的结果。 替代:

ax.text(x0, y0, str(y0), ha="center", va="bottom", color=color, clip_on=True)

在此处输入图像描述

您也可以在这里使用方便的Axes.bar_label方法,只需几行即可完成此操作。

由于seaborn不返回BaContainer对象给我们,我们需要通过Axes.containers属性从Axes object 访问它们。

import matplotlib.pyplot as plt
import seaborn as sns

data = sns.load_dataset("titanic")
fig, ax = plt.subplots()
sns.countplot(data=data, x="class", hue="who", ax=ax)

for bar_contain in ax.containers:
    ax.bar_label(bar_contain)

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM