Python 画 直方图/条形图/柱状图

来源:互联网 发布:神盾网络验证山寨 编辑:程序博客网 时间:2024/06/05 03:29

1.单个条形图并显示数字

import matplotlib.pyplot as pltname_list = ['lambda=0', 'lambda=0.05', 'lambda=0.1', 'lambda=0.5']num_list = [52.4, 57.8, 59.1, 54.6]rects=plt.bar(range(len(num_list)), num_list, color='rgby')# X轴标题index=[0,1,2,3]index=[float(c)+0.4 for c in index]plt.ylim(ymax=80, ymin=0)plt.xticks(index, name_list)plt.ylabel("arrucay(%)") #X轴标签for rect in rects:    height = rect.get_height()    plt.text(rect.get_x() + rect.get_width() / 2, height, str(height)+'%', ha='center', va='bottom')plt.show()


2.画对比条形图中文显示标注并保存为图片

import matplotlib as mplmpl.use('Agg')import matplotlib.pyplot as pltimport numpy as np# 必须配置中文字体,否则会显示成方块# 注意所有希望图表显示的中文必须为unicode格式custom_font = mpl.font_manager.FontProperties(fname='zh.ttf')font_size = 10 # 字体大小fig_size = (8, 6) # 图表大小names = (u'直接作差', u'优化后') # 姓名subjects = (u'时间/秒(每预测100张图片)', u'精度/百分比') # 科目scores = ((65.2, 52.4), (40.5, 76.8)) # 成绩# 更新字体大小mpl.rcParams['font.size'] = font_size# 更新图表大小mpl.rcParams['figure.figsize'] = fig_size# 设置柱形图宽度bar_width = 0.30index = np.arange(len(scores[0]))# 绘制「小明」的成绩rects1 = plt.bar(index, scores[0], bar_width, color='#0072BC', label=names[0])# 绘制「小红」的成绩rects2 = plt.bar(index + bar_width, scores[1], bar_width, color='#ED1C24', label=names[1])# X轴标题plt.xticks(index + bar_width, subjects, fontproperties=custom_font)# Y轴范围plt.ylim(ymax=100, ymin=0)# 图表标题plt.title(u'改进前后对比', fontproperties=custom_font)# 图例显示在图表下方plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.03), fancybox=True, ncol=5, prop=custom_font)# 添加数据标签def add_labels(rects):    for rect in rects:        height = rect.get_height()        plt.text(rect.get_x() + rect.get_width() / 2, height, height, ha='center', va='bottom')        # 柱形图边缘用白色填充,纯粹为了美观        rect.set_edgecolor('white')add_labels(rects1)add_labels(rects2)# 图表输出到本地plt.savefig('scores_par.png')plt.show()



阅读全文
0 0