python+matplotlib绘制带误差线的柱状图

import numpy as np
import matplotlib.pyplot as plt
# 平均房价, 波动范围
prices = (12, 15, 11, 10, 8)
tolerance_p = (3, 4, 3, 2.5, 3.5)
# 平均工资,波动范围
wages = (6, 10, 7, 8, 6)
tolerance_w = (2, 5, 4, 4, 4)

index = np.arange(len(prices))
width = 0.4
cities = ('北京', '上海', '广州', '深圳', '杭州')
# 绘制房价柱状图和收入柱状图
# yerr用来指定误差范围, 与结果图中的误差线对应
bar_prices = plt.bar(index, prices, width, color='#02ccfe', yerr=tolerance_p)
bar_wages = plt.bar(index+width, wages, width, color='#c760ff', yerr=tolerance_w)
plt.xlabel('城市名称', fontproperties='simhei', fontsize=16)
plt.ylabel('金额(万元)', fontproperties='simhei', fontsize=16)
plt.title('收入与房价', fontproperties='kaiti', fontsize=24)
plt.xticks(index+width/2, cities, fontproperties='microsoft yahei', fontsize=12)

# 创建图例
plt.legend([bar_prices, bar_wages], ['房价', '月收入'], prop='kaiti')
def add_text(bars, tol):
    for index, bar in enumerate(bars):
        x = bar.get_x() + width/2
        h = bar.get_height()
        # 在每个柱的误差线上下两侧显示文本, ha、va表示水平、垂直对其方式
        plt.text(x, h+tol[index], str(h+tol[index]), color='k', ha='center')
        plt.text(x, h-tol[index]-1, str(h-tol[index]), color='w', ha='center', va='bottom')

add_text(bar_prices, tolerance_p)
add_text(bar_wages, tolerance_w)
plt.show()

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值