修复条形图 matplotlib 的标注功能

Fixing the labeling function of bar charts matplotlib

我想创建 2 个由这两个列表组成的条形图并且我构建了它。

d_prime = [-0.53, -1.89, 0.76, 1.66]
d_prime_2 = [-0.69, 0.23, -0.88, 1.34]

plt.figure()
fig = plt.gcf()
fig.set_size_inches(11, 8)

times = ("1400", "2000", "3000", "4000")
ypos = np.arange(len(times))

plt.subplot(2,2,1)
bar_1= plt.bar(ypos, d_prime, align='center', alpha=0.5)
plt.title('First half of the D primes of subject {}'.format(i+3))
plt.xticks(x, index, rotation = 0)

plt.legend("D' primes 1st")

plt.subplot(2,2,2)
bar_2 = plt.bar(ypos, d_prime_2, align='center', alpha=0.5, color = 'cyan')
plt.title('Second half of the D primes of subject {}'.format(i+3))
plt.xticks(ypos, times)
plt.legend("D' primes 2nd")

def autolabel(rects):
    ##Attach a text label above each bar in *rects*, displaying its height.
    for rect in rects:
        height = rect.get_height()
        plt.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')

autolabel(bar_1)
autolabel(bar_2)
plt.show()

我尝试这样做,但它看起来像:

我想清楚地标记 bar_1 和 bar_2,但它只标记 bar_2。

你能帮我修复这个功能吗?或者你有什么建议吗?

问题出在第二个子图是活动轴。

一个不会过多更改代码的快速修复方法是在 autolabel 中为轴添加一个参数:

ax1 = plt.subplot(2,2,1)
...
ax2 = plt.subplot(2,2,2)
...
def autolabel(ax, rects):
    ...
    ax.annotate(...)

autolabel(ax1, bar1)
autolabel(ax2, bar2)

或者在显示条形图之前简单地定义函数autolabel,并在每个子图语句中调用该函数。

def autolabel(rects):
    ...

...
plt.subplot(1,2,1)
bar_1 = ...
autolabel(bar_1)  # add annotations on the first subplot (the active one)

plt.subplot(1,2,2)  # now the current axes is the second one
bar_2 = ...
autolabel(bar_2)  # add annotations on the second subplot