Absolute Values and Percentage Values Side by Side in Bar Chart Matplotlib

女生的网名这么多〃 提交于 2021-01-29 15:16:01

问题


I would like to count on your help for the following problem that I have been facing. I've been trying, but without success, to put absolute values and percentage values side by side. Where 53 and 47 are percentage values and would be outside the parentheses and 17 and 15 are absolute values and would be inside the parentheses. Both absolute values and percentage values are already known, therefore, there is no need for any calculation to obtain them. I leave my code here for you to see how far I managed to go. This is the error:

TypeError: __init__() got multiple values for argument 'xytext'
x_axis = ["MJO Active","MJO Inactive"]
y_axis = [53,47]

fig, ax = plt.subplots(figsize=(10,7))
palette = sns.color_palette(["#55a868"])
rects = sns.barplot(x_axis,y_axis, linewidth = 0, color='#55a868')

ax.tick_params(axis='both', which='major', pad=1)
plt.xlabel('MJO Activity', fontsize=24)
plt.xticks(rotation="horizontal", size = 20)

ax.locator_params(axis='y', integer=True)
plt.ylabel('Percentage of Events (%)', fontsize=24)
plt.yticks(size = 18)
plt.ylim(0,60)

plt.title('ONDJFMA - 1996/2014',fontsize=24)
 
ax.get_xaxis().set_label_coords(0.5,-0.10)
ax.get_yaxis().set_label_coords(-0.06,0.5)

values = [17, 15]
v = 0
for rect in rects.patches:
    rects.annotate(format(rect.get_height(), '.0f'), 
                   (rect.get_x() + rect.get_width() / 2., 1.0*rect.get_height()), 
                   '%d(%d)' % (int(rect.get_height()), values[v]), ha = 'center', va='bottom', fontsize = 20, 
                   xytext = (0, 0), 
                   textcoords = 'offset points')
    v = v + 1

plt.show()

回答1:


You were nearly there. We link bar rectangles, percentage values, and absolute values with zip, then use f-string formatting for the display:

...
values = [17, 15]

for rect, perc, vals  in zip(rects.patches, y_axis, values):    
    rects.annotate(f"{perc}% ({vals})", (rect.get_x() + rect.get_width() / 2., rect.get_height()),
                 ha='center', va='center', fontsize=20, color='black', xytext=(0, 10),
                 textcoords='offset points')

plt.tight_layout()
plt.show()

Sample output:



来源:https://stackoverflow.com/questions/65655829/absolute-values-and-percentage-values-side-by-side-in-bar-chart-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!