import seaborn as sns
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8,4))
ax = sns.countplot(my_data, x="some_feature",stat="percent")
ax.bar_label(container=ax.containers[0],label_type="center") # <- this line
我无法理解
ax.containers[0]
对象的来源。我一直在浏览 Matplotlib 文档,但找不到任何对 .containers
对象的引用以及如何使用它来访问 bar 容器对象的约定。我看到有关于 matplotlib.container
的文档,但有人可以解释为什么使用 .containers
代替 .container
吗?
当您创建 matplotlib
Axes
对象时,它会被初始化为 .containers
为空列表。创建条形图时,matplotlib 将 BarContainer
添加到 .containers
列表中。
import matplolib.pyplot as plt
fig, ax = plt.subplots()
print(ax.containers) # []
ax.bar(range(4), range(4))
print(ax.containers) # [<BarContainer object of 4 artists>]
查看
matplotlib.axes.Axes.bar
源代码,我们看到这些行:
bar_container = BarContainer(patches, errorbar, datavalues=datavalues,
orientation=orientation,
label=bar_container_label)
self.add_container(bar_container)
(这里,
self
是Axes
对象。)