在 Matplotlib 的条形图顶部放置增长百分比

塞巴斯蒂安·戈斯林

我从8栋独立的建筑数据的柱状图,数据按年分离,我想放置的增长每个建筑经历了去年的条形图的顶部。

我目前写的是:

n_groups = 8

numbers_2017 = (122,96,42,23,23,22,0,0)

numbers_2018 = (284,224,122,52,41,24,3,1)


fig, ax = plt.subplots(figsize=(15, 10))

index = np.arange(n_groups)
bar_width = 0.35


events2017 = plt.bar(index, numbers_2017, bar_width,
                 alpha=0.7,
                 color='#fec615',
                 label='2017')

events2018 = plt.bar(index + bar_width, numbers_2018, bar_width,
                 alpha=0.7,
                 color='#044a05',
                 label='2018')

labels = ("8 specific buildings passed as strings")

labels = [ '\n'.join(wrap(l, 15)) for l in labels ]

plt.ylabel('Total Number of Events', fontsize=18, fontweight='bold', color = 'white')

plt.title('Number of Events per Building By Year\n', fontsize=20, fontweight='bold', color = 'white')

plt.xticks(index + bar_width / 2)

plt.yticks(color = 'white', fontsize=12)

ax.set_xticklabels((labels),fontsize=12, fontweight='bold', color = 'white')

plt.legend(loc='best', fontsize='xx-large')

plt.tight_layout()
plt.show()

在这里查看类似的问题,其中许多将总计数拆分为所有条形,而我只是试图在最近一年(在这种情况下为 2018 年)之上获得正(或负)增长百分比。 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

我在网上找到了这个很好的例子,但是它完全按照我之前解释的那样做,将图表中的百分比分开:

totals = []

# find the values and append to list
for i in ax.patches:
    totals.append(i.get_height())

# set individual bar lables using above list
total = sum(totals)

# set individual bar lables using above list
for i in ax.patches:
    # get_x pulls left or right; get_height pushes up or down
    ax.text(i.get_x()-.03, i.get_height()+.5, \
            str(round((i.get_height()/total)*100, 1))+'%', fontsize=15,
                color='dimgrey')

请让我知道我是否可以列出任何有帮助的示例或图像,如果这是一个骗局,请不要犹豫,将我发送到(相关)原件,我可以关闭这个问题,谢谢!

赖恩·K。

我想你自己用你给出的代码的第二部分给出了答案。您唯一需要做的就是将ax上面的文本更改为您想要的对象,在本例中为events2018.

totals = []

for start, end in zip(events2017.patches, events2018.patches):
    if start.get_height() != 0:
        totals.append( (end.get_height() - start.get_height())/start.get_height() * 100)
    else:
        totals.append("NaN")

# set individual bar lables using above list
for ind, i in enumerate(events2018.patches):
    # get_x pulls left or right; get_height pushes up or down
    if totals[ind] != "NaN":
        plt.text(i.get_x(), i.get_height()+.5, \
            str(round((totals[ind]), 1))+'%', fontsize=15,
                color='dimgrey')
    else: 
        plt.text(i.get_x(), i.get_height()+.5, \
                 totals[ind], fontsize=15, color='dimgrey')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章