我有一个条形图,其中有来自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年)之上。
我发现了一个出色的示例online,但是它确实如我之前解释的那样,将图表中的百分比分开:
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')
请让我知道我是否可以列出任何有帮助的示例或图片,如果这是重复的,请立即将我发送给(相关)原件,我可以关闭此问题,谢谢!< / p>
答案 0 :(得分:1)
我认为您用给出的第二部分代码自己给出了答案。
您唯一要做的就是将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')