網站首頁 編程語言 正文
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)
原文鏈接:https://blog.csdn.net/quintus0505/article/details/123521138
相關推薦
- 2022-10-10 React?Hooks鉤子中API的使用示例分析_React
- 2022-05-04 R語言邏輯型運算的實現_R語言
- 2022-12-14 Android?liveData與viewBinding使用教程_Android
- 2022-04-30 DataGridView自動設定列寬和行高_C#教程
- 2022-03-28 IPython?8.0?Python?命令行交互工具_python
- 2022-09-05 C語言中如何實現單鏈表刪除指定結點_C 語言
- 2022-04-23 二次開發element el-tooltip+span 超出文本部分顯示省略號鼠標懸浮顯示全部內容
- 2023-06-18 C#實現不同窗體之間傳遞參數_C#教程
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支