简体   繁体   English

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

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

I need to add bar value to the right of barh() or top of the plt.bar(). 我需要在barh()的右侧或plt.bar()的顶部添加bar值。 However, I have custom xTicks. 但是,我有自定义xTicks。 How should I do that? 我应该怎么做?

So I have 4 subplot that their x or y ticks are customized, following code iterate well but text position is not correct because of 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()

Thanks. 谢谢。

EDIT:When I try to save it as a picture, text placement becomes worst 编辑:当我尝试将其另存为图片时,文字放置变得最糟

The y coordinate of the text needs to coincide with the y coordinate of the bar it has to label. 文本的y坐标必须与其必须标记的条的y坐标一致。 So you cannot put 3 for all texts but instead could eg use a loop variable obtain that coordinate. 因此,您不能对所有文本都输入3 ,而是可以例如使用循环变量获取该坐标。

I cleaned up your code a bit because it was rather hard to read. 我整理了一下您的代码,因为它很难阅读。

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()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM