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实现的简单hangman游戏实例
Jun 28 Python
十条建议帮你提高Python编程效率
Feb 16 Python
Python检测生僻字的实现方法
Oct 23 Python
Python中with及contextlib的用法详解
Jun 08 Python
Python对字符串实现去重操作的方法示例
Aug 11 Python
python PyTorch参数初始化和Finetune
Feb 11 Python
用Python实现读写锁的示例代码
Nov 05 Python
解决pycharm下os.system执行命令返回有中文乱码的问题
Jul 07 Python
用Python抢火车票的简单小程序实现解析
Aug 14 Python
Python unittest 自动识别并执行测试用例方式
Mar 09 Python
使用python matplotlib 画图导入到word中如何保证分辨率
Apr 16 Python
python批量更改目录名/文件名的方法
Apr 18 Python
python绘制简单直方图(质量分布图)的方法
Python绘制散乱的点构成的图的方法
Python可视化动图组件ipyvizzu绘制惊艳的可视化动图
Python探索生命起源 matplotlib细胞自动机动画演示
Apr 21 #Python
使用python绘制横竖条形图
python多次执行绘制条形图
Apr 20 #Python
Python 数据可视化工具 Pyecharts 安装及应用
You might like
php中文本数据翻页(留言本翻页)
2006/10/09 PHP
PHP6 中可能会出现的新特性预览
2014/04/04 PHP
JS Pro-深入面向对象的程序设计之继承的详解
2013/05/07 Javascript
jquery事件重复绑定的快速解决方法
2014/01/03 Javascript
javascript类型转换使用方法
2014/02/08 Javascript
分享2个jQuery插件--jquery.fileupload与artdialog
2014/12/26 Javascript
微信小程序中的onLoad详解及简单实例
2017/04/05 Javascript
微信小程序实现MUI数字输入框效果
2018/01/31 Javascript
Bootstrap标签页(Tab)插件切换echarts不显示问题的解决
2018/07/13 Javascript
详解Webpack-dev-server的proxy用法
2018/09/08 Javascript
在angularJs中进行数据遍历的2种方法
2018/10/08 Javascript
每个 JavaScript 工程师都应懂的33个概念
2018/10/22 Javascript
layui表单验证select下拉框实现验证的方法
2019/09/05 Javascript
基于原生JS封装的Modal对话框插件的示例代码
2020/09/09 Javascript
[00:32]2018DOTA2亚洲邀请赛出场——VP
2018/04/04 DOTA
[34:39]Secret vs VG 2018国际邀请赛淘汰赛BO3 第二场 8.23
2018/08/24 DOTA
Python命令行参数解析模块getopt使用实例
2015/04/13 Python
浅述python中argsort()函数的实例用法
2017/03/30 Python
python模拟登录并且保持cookie的方法详解
2017/04/04 Python
python中使用%与.format格式化文本方法解析
2017/12/27 Python
详解tensorflow实现迁移学习实例
2018/02/10 Python
Python使用sorted对字典的key或value排序
2018/11/15 Python
Python计算不规则图形面积算法实现解析
2019/11/22 Python
python中如何写类
2020/06/29 Python
利用css3如何设置没有上下边的列表间隔线
2017/07/03 HTML / CSS
德国二手设计师时装和复古时装跳蚤市场:Mädchenflohmarkt
2020/11/09 全球购物
保安员岗位职责
2013/11/17 职场文书
优秀大学生推荐信范文
2013/11/28 职场文书
个人优缺点自我评价
2014/01/27 职场文书
认识深刻的检讨书
2014/02/16 职场文书
商学院大学生求职的自我评价
2014/03/12 职场文书
办理信用卡工作证明
2014/09/30 职场文书
政风行风评议心得体会
2014/10/21 职场文书
计划生育工作总结2015
2015/04/03 职场文书
2015年高三年级组工作总结
2015/07/21 职场文书
叶县这家生产军用电台的兵工厂,人称“四机部”,走出一上将
2022/02/18 无线电