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()