[英]python bar chart total label on bar
调用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.