Python matplotlib实现条形统计图
作者:quintus0505
这篇文章主要为大家详细介绍了Python matplotlib实现条形统计图,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
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)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。