Python matplotlib绘制条形统计图 处理多个实验多组观测值


Posted in Python onApril 21, 2022

效果图展示如下:

Python matplotlib绘制条形统计图 处理多个实验多组观测值

该代码可以处理多个实验多组观测值的展示,代码如下:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import MultipleLocator

def plot_bar(experiment_name, bar_name, bar_value, error_value=None,):
    """

    Args:
        experiment_name: x_labels
        bar_name: legend name
        bar_value: list(len(experiment_name), each element contains a np.array(),
                   which contains bar value in each group
        error_value: list(len(experiment_name), each element contains a np.array(),
                   which contains error value in each group
    Returns:

    """

    # 用于正常显示中文标签
    # plt.rcParams["font.sans-serif"]=['SimHei']

    colors = ['lightsteelblue', 'cornflowerblue', 'royalblue', 'blue', 'mediumblue', 'darkblue', 'navy', 'midnightblue',
              'lavender', ]

    assert len(bar_value[0]) <= len(colors)  # if not try to add color to 'colors'

    plt.rcParams['axes.unicode_minus'] = False
    plt.style.use('seaborn')
    font = {'weight': 'normal', 'size': 20, }
    font_title = {'weight': 'normal', 'size': 28, }
    # bar width
    width = 0.2
    # groups of data
    x_bar = np.arange(len(experiment_name))
    # create figure
    plt.figure(figsize=(10, 9))

    ax = plt.subplot(111)  # 假如设置为221,则表示创建两行两列也就是4个子画板,ax为第一个子画板

    # plot bar

    bar_groups = []
    value = []
    for i in range(len(bar_value[0])):
        for j in range(len(experiment_name)):
            value.append(bar_value[j][i])
        group = ax.bar(x_bar - (len(experiment_name)-3-i)*width, copy.deepcopy(value), width=width, color=colors[i], label=bar_name[i])
        bar_groups.append(group)
        value.clear()


    # add height to each bar
    i = j = 0
    for bars in bar_groups:
        j = 0
        for rect in bars:
            x = rect.get_x()
            height = rect.get_height()
            # ax.text(x + 0.1, 1.02 * height, str(height), fontdict=font)
            # error bar
            if error_value:
                ax.errorbar(x + width / 2, height, yerr=error_value[j][i], fmt="-", ecolor="black",
                            elinewidth=1.2, capsize=2,
                            capthick=1.2)
            j += 1
        i += 1

    # 设置刻度字体大小
    plt.xticks(fontsize=15)
    plt.yticks(fontsize=18)
    # 设置x轴的刻度
    ax.set_xticks(x_bar)
    ax.set_xticklabels(experiment_name, fontdict=font)

    # 设置y轴的刻标注
    ax.set_ylabel("Episode Cost", fontdict=font_title)
    ax.set_xlabel('Experiment', fontdict=font_title)

    # 是否显示网格
    ax.grid(False)

    # 拉伸y轴
    ax.set_ylim(0, 7.5)
    # 把轴的刻度间隔设置为1,并存在变量里
    y_major_locator = MultipleLocator(2.5)
    ax.yaxis.set_major_locator(y_major_locator)

    # 设置标题
    plt.suptitle("Cost Comparison", fontsize=30, horizontalalignment='center')

    plt.subplots_adjust(left=0.11, bottom=0.1, right=0.95, top=0.93, wspace=0.1, hspace=0.2)
    # 设置边框线宽为2.0
    ax.spines['bottom'].set_linewidth('2.0')
    # 添加图例
    ax.legend(loc='upper left', frameon=True, fontsize=19.5)
    # plt.savefig("test.png")
    plt.show()
    plt.legend()

if __name__ == "__main__":
    test_experiment_name = ["Test 1", "Test 2", "Test 3", "Test 4"]
    test_bar_name = ['A', "B", "C"]
    test_bar_value = [
        np.array([1, 2, 3]),
        np.array([4, 5, 6]),
        np.array([3, 2, 4]),
        np.array([5, 2, 2])
    ]
    test_error_value = [
        np.array([1, 1, 2]),
        np.array([0.2, 0.6, 1]),
        np.array([0, 0, 0]),
        np.array([0.5, 0.2, 0.2])
    ]
    plot_bar(test_experiment_name, test_bar_name, test_bar_value, test_error_value)

以上就是本文的全部内容,希望对大家的学习有所帮助。


Tags in this post...

Python 相关文章推荐
python网络编程示例(客户端与服务端)
Apr 24 Python
Python中使用logging模块打印log日志详解
Apr 05 Python
Python字符串中查找子串小技巧
Apr 10 Python
使用实现XlsxWriter创建Excel文件并编辑
May 04 Python
用Python将mysql数据导出成json的方法
Aug 21 Python
详解Python中的正斜杠与反斜杠
Aug 09 Python
python实现的Iou与Giou代码
Jan 18 Python
python+selenium定时爬取丁香园的新型冠状病毒数据并制作出类似的地图(部署到云服务器)
Feb 09 Python
Python networkx包的实现
Feb 14 Python
python 装饰器功能与用法案例详解
Mar 06 Python
利用matplotlib为图片上添加触发事件进行交互
Apr 23 Python
什么是Python变量作用域
Jun 03 Python
python绘制简单直方图(质量分布图)的方法
Python绘制散乱的点构成的图的方法
Python可视化动图组件ipyvizzu绘制惊艳的可视化动图
Python探索生命起源 matplotlib细胞自动机动画演示
Apr 21 #Python
使用python绘制横竖条形图
python多次执行绘制条形图
Apr 20 #Python
Python 数据可视化工具 Pyecharts 安装及应用
You might like
php读取html并截取字符串的简单代码
2009/11/30 PHP
PHP输出时间差函数代码
2013/01/28 PHP
解析PHP中的正则表达式以及模式匹配
2013/06/19 PHP
PHP采用自定义函数实现遍历目录下所有文件的方法
2014/08/19 PHP
百度工程师讲PHP函数的实现原理及性能分析(三)
2015/05/13 PHP
javascript 放大镜效果js组件 qsoft.PopBigImage.v0.35 加入了chrome支持
2009/04/07 Javascript
JS 日期比较大小的简单实例
2014/01/13 Javascript
javascript 数组操作详解
2015/01/29 Javascript
jQuery AjaxUpload 上传图片代码
2016/02/02 Javascript
AngularJs 60分钟入门基础教程
2016/04/03 Javascript
jQuery插件HighCharts实现气泡图效果示例【附demo源码】
2017/03/13 Javascript
vue.js开发环境搭建教程
2017/05/04 Javascript
利用纯JS实现像素逐渐显示的方法示例
2017/08/14 Javascript
JavaScript实现模态对话框实例
2020/01/13 Javascript
微信小程序多列表渲染数据开关互不影响的实现
2020/06/05 Javascript
vue-openlayers实现地图坐标弹框效果
2020/09/24 Javascript
[01:02:46]VGJ.S vs NB 2018国际邀请赛小组赛BO2 第二场 8.18
2018/08/19 DOTA
python中lambda与def用法对比实例分析
2015/04/30 Python
python如何让类支持比较运算
2018/03/20 Python
python自动截取需要区域,进行图像识别的方法
2018/05/17 Python
OpenCV+Python识别车牌和字符分割的实现
2019/01/31 Python
用python做游戏的细节详解
2019/06/25 Python
Python多线程正确用法实例解析
2020/05/30 Python
应届毕业生通用的自荐书范文
2014/02/07 职场文书
高中历史教学反思
2014/02/08 职场文书
2014年元旦感言
2014/03/06 职场文书
毕业生欢送会主持词
2014/03/31 职场文书
项目建议书模板
2014/05/12 职场文书
优秀毕业生求职信
2014/06/05 职场文书
银行主办会计岗位职责
2014/08/13 职场文书
导游词怎么写
2015/02/04 职场文书
拾金不昧通报表扬范文
2015/05/05 职场文书
离婚案件上诉状
2015/05/23 职场文书
Python网络编程之ZeroMQ知识总结
2021/04/25 Python
浅谈Python 中的复数问题
2021/05/19 Python
动视暴雪取消疫苗禁令 让所有员工返回线下工作
2022/04/03 其他游戏