当有自定义刻度时,将条形值添加到子条形图

Adding bar value to subbar plot when there is a custom tick

我需要在 barh() 的右侧或 plt.bar() 的顶部添加 bar 值。 但是,我有自定义 xTicks。我应该怎么做?

所以我有 4 个子图,它们的 x 或 y 刻度是自定义的,下面的代码迭代很好但文本位置不正确,因为 xticks。

import matplotlib.pyplot as plt
fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
[subax.yaxis.set(ticks=range(1,4),ticklabels=['a','b','c']) for ax in axes for subax in ax]
# Data
data=list([([8, 9, 8]), ([23, 26, 2]), ([33,37,33]), ([40, 45, 40])])
barplot=[subax.barh([1,2,3],list(data.pop())) for ax in axes for subax in ax]

for ax in axes:
    for subax in ax:
        count=0
        [[subax.text(rect.get_width()+2,3, str(rect.get_width()))] for rect in barplot[count]]
    count+=1
plt.show()

谢谢。

编辑:当我尝试将其另存为图片时,文本位置变得最差

文本的 y 坐标需要与其标记的条形的 y 坐标一致。所以你不能把 3 用于所有文本,而是可以例如使用循环变量获取该坐标。

我稍微清理了你的代码,因为它很难读。

import matplotlib.pyplot as plt
fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)

data=list([([8, 9, 8]), ([23, 26, 2]), ([33,37,33]), ([40, 45, 40])])
barplot=[ax.barh(['a','b','c'],list(data.pop())) for ax in axes.flat]

for i, ax in enumerate(axes.flat):
    for j, rect in enumerate(barplot[i]):
        ax.text(rect.get_width(), j, str(rect.get_width()))
plt.show()