Matplotlib:查找包含BarContainer的子图

3

我正在尝试编写一个自动标签函数,就像这个示例中的那个一样(https://matplotlib.org/examples/api/barchart_demo.html),它看起来如下:

def autolabel(barContainer):
"""
Attach a text label above each bar displaying its height
"""

for rect, yerr in zip(barContainer, barContainer.errorbar.get_children()[0].get_segments()):
    error  = yerr[1,1]- yerr[:,1].mean() # print error
    height = rect.get_height()

    ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
            '{:.1f} +/- {:.1f}'.format(height, error),
            family="monospace",
            ha='center', va='bottom')

然而,当我使用不同的子图(比如叫做ax2)调用该函数时,会出现NameError错误。我希望能够查找包含BarContainer的ax,而不必在我的函数中显式地传递ax=ax2参数。
有人知道这是否可能吗?


你需要将轴作为参数传递给函数。 - DavidG
1个回答

2

不需要修改函数本身的内容,只需添加一个函数接受的额外参数。这个参数应该是 axes

def autolabel(barContainer, ax):

    """
    Attach a text label above each bar displaying its height
    """

    for rect, yerr in zip(barContainer, barContainer.errorbar.get_children()[0].get_segments()):
        error  = yerr[1,1]- yerr[:,1].mean() # print error
        height = rect.get_height()

        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                '{:.1f} +/- {:.1f}'.format(height, error),
                family="monospace",
                ha='center', va='bottom')

然后,当你想调用这个函数时:

fig, (ax, ax2) = plt.subplots(1, 2)
# Some plotting with ax
autolabel(barContainer, ax)

# Some plotting with ax2
autolabel(barContainer, ax2)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,