python 条形图图注怎么集中,如何在条形图上的条形上方写文本(Python)?

本文介绍如何在Matplotlib创建的柱状图中,上方正确显示对应于柱子的计数值,针对两组数据(快速完成任务的误差率和慢速完成任务的误差率)。提供了代码示例,包括使用`text()`函数添加计数到每个柱子上方。
摘要由CSDN通过智能技术生成

I have this graph:

d891989a8399b13d84a05dfa92922ca8.png

I want to write the count above each column. These values are in the first and second lists. Can you help me solve this problem? I tried something without success.

This is the code for the graph:

countListFast = [1492.0, 497.0, 441.0, 218.0, 101.0, 78.0, 103.0]

countListSlow = [1718.0, 806.0, 850.0, 397.0, 182.0, 125.0, 106.0]

errorRateListOfFast = ['9.09', '9.09', '9.38', '9.40', '7.89', '8.02', '10.00']

errorRateListOfSlow = ['10.00', '13.04', '14.29', '12.50', '14.29', '14.53', '11.11']

opacity = 0.4

bar_width = 0.35

plt.xlabel('Tasks')

plt.ylabel('Error Rate')

plt.xticks(range(len(errorRateListOfFast)),('[10-20)', '[20-30)', '[30-50)', '[50-70)','[70-90)', '[90-120)', ' [120 < )'), rotation=30)

plt.bar(np.arange(len(errorRateListOfFast))+ bar_width, errorRateListOfFast, bar_width, align='center', alpha=opacity, color='b', label='Fast <= 6 sec.')

plt.bar(range(len(errorRateListOfSlow)), errorRateListOfSlow, bar_width, align='center', alpha=opacity, color='r', label='Slower > 6 sec.')

plt.legend()

plt.tight_layout()

plt.show()

解决方案

plt.bar() returns a list of rectangles that can be used to position suitable text above each of the bars as follows:

import matplotlib.pyplot as plt

import numpy as np

countListFast = [1492.0, 497.0, 441.0, 218.0, 101.0, 78.0, 103.0]

countListSlow = [1718.0, 806.0, 850.0, 397.0, 182.0, 125.0, 106.0]

errorRateListOfFast = ['9.09', '9.09', '9.38', '9.40', '7.89', '8.02', '10.00']

errorRateListOfSlow = ['10.00', '13.04', '14.29', '12.50', '14.29', '14.53', '11.11']

opacity = 0.4

bar_width = 0.35

plt.xlabel('Tasks')

plt.ylabel('Error Rate')

plt.xticks(range(len(errorRateListOfFast)),('[10-20)', '[20-30)', '[30-50)', '[50-70)','[70-90)', '[90-120)', ' [120 < )'), rotation=30)

bar1 = plt.bar(np.arange(len(errorRateListOfFast))+ bar_width, errorRateListOfFast, bar_width, align='center', alpha=opacity, color='b', label='Fast <= 6 sec.')

bar2 = plt.bar(range(len(errorRateListOfSlow)), errorRateListOfSlow, bar_width, align='center', alpha=opacity, color='r', label='Slower > 6 sec.')

# Add counts above the two bar graphs

for rect in bar1 + bar2:

height = rect.get_height()

plt.text(rect.get_x() + rect.get_width()/2.0, height, '%d' % int(height), ha='center', va='bottom')

plt.legend()

plt.tight_layout()

plt.show()

Giving you:

0971de33b81087aa27b1b0d7ed0e110a.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值