[519]matplotlib(三)

2023-11-05

  • 带误差线的条形图
import matplotlib.pyplot as plt
 
# 输入数据
mean_values = [1, 2, 3]
variance = [0.2, 0.4, 0.5]
bar_labels = ['bar 1', 'bar 2', 'bar 3']
 
# 绘制图形
x_pos = list(range(len(bar_labels)))
plt.bar(x_pos, mean_values, yerr=variance, align='center', alpha=0.5)
 
plt.grid()
 
# 设置y轴高度
max_y = max(zip(mean_values, variance)) # returns a tuple, here: (3, 5)
plt.ylim([0, (max_y[0] + max_y[1]) * 1.1])
 
# 设置轴标签和标题
plt.ylabel('variable y')
plt.xticks(x_pos, bar_labels)
plt.title('Bar plot with error bars')
 
plt.show()
#plt.savefig('./my_plot.png')

image.png

  • 带误差线的水平条形图
from matplotlib import pyplot as plt
import numpy as np
 
# 输入数据
mean_values = [1, 2, 3]
std_dev = [0.2, 0.4, 0.5]
bar_labels = ['bar 1', 'bar 2', 'bar 3']
 
fig = plt.figure(figsize=(8,6))
 
# 绘制条形图
y_pos = np.arange(len(mean_values))
y_pos = [x for x in y_pos]
plt.yticks(y_pos, bar_labels, fontsize=10)
plt.barh(y_pos, mean_values, xerr=std_dev,
         align='center', alpha=0.4, color='g')
 
# 标签
plt.xlabel('measurement x')
t = plt.title('Bar plot with standard deviation')
plt.ylim([-1,len(mean_values)+0.5])
plt.xlim([0, 4])
plt.grid()
 
plt.show()

image.png

  • 背对背条形图绘制
from matplotlib import pyplot as plt
import numpy as np
 
# 输入数据
X1 = np.array([1, 2, 3])
X2 = np.array([2, 2, 3])
 
 
bar_labels = ['bar 1', 'bar 2', 'bar 3']
 
fig = plt.figure(figsize=(8,6))
 
# 绘制
y_pos = np.arange(len(X1))
y_pos = [x for x in y_pos]
plt.yticks(y_pos, bar_labels, fontsize=10)
 
 
plt.barh(y_pos, X1,
         align='center', alpha=0.4, color='g')
 
# 我们简单的取反,画第二个条形图
plt.barh(y_pos, -X2,
         align='center', alpha=0.4, color='b')
 
# 标签
plt.xlabel('measurement x')
t = plt.title('Bar plot with standard deviation')
plt.ylim([-1,len(X1)+0.1])
plt.xlim([-max(X2)-1, max(X1)+1])
plt.grid()
 
plt.show()

image.png

  • 条形图群
import matplotlib.pyplot as plt
 
# 输入数据
green_data = [1, 2, 3]
blue_data = [3, 2, 1]
red_data = [2, 3, 3]
labels = ['group 1', 'group 2', 'group 3']
 
# 设置条形图的位置和宽度
pos = list(range(len(green_data)))
width = 0.2
 
# 绘制
fig, ax = plt.subplots(figsize=(8,6))
 
plt.bar(pos, green_data, width,
                 alpha=0.5,
                 color='g',
                 label=labels[0])
 
plt.bar([p + width for p in pos], blue_data, width,
                 alpha=0.5,
                 color='b',
                 label=labels[1])
 
plt.bar([p + width*2 for p in pos], red_data, width,
                 alpha=0.5,
                 color='r',
                 label=labels[2])
 
# 设置标签和距离
ax.set_ylabel('y-value')
ax.set_title('Grouped bar plot')
ax.set_xticks([p + 1.5 * width for p in pos])
ax.set_xticklabels(labels)
 
# 设置x,y轴限制
plt.xlim(min(pos)-width, max(pos)+width*4)
plt.ylim([0, max(green_data + blue_data + red_data) * 1.5])
 
# 绘制
plt.legend(['green', 'blue', 'red'], loc='upper left')
plt.grid()
plt.show()

image.png

  • 叠加条形图
import matplotlib.pyplot as plt
 
blue_data = [100,120,140]
red_data = [150,120,190]
green_data = [80,70,90]
 
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(10,5))
 
bar_width = 0.5
 
# positions of the left bar-boundaries
bar_l = [i+1 for i in range(len(blue_data))]
 
# positions of the x-axis ticks (center of the bars as bar labels)
tick_pos = [i+(bar_width/2) for i in bar_l]
 
###################
## Absolute count
###################
 
ax1.bar(bar_l, blue_data, width=bar_width,
        label='blue data', alpha=0.5, color='b')
ax1.bar(bar_l, red_data, width=bar_width,
        bottom=blue_data, label='red data', alpha=0.5, color='r')
ax1.bar(bar_l, green_data, width=bar_width,
        bottom=[i+j for i,j in zip(blue_data,red_data)], label='green data', alpha=0.5, color='g')
 
plt.sca(ax1)
plt.xticks(tick_pos, ['category 1', 'category 2', 'category 3'])
 
ax1.set_ylabel("Count")
ax1.set_xlabel("")
plt.legend(loc='upper left')
plt.xlim([min(tick_pos)-bar_width, max(tick_pos)+bar_width])
plt.grid()
 
# rotate axis labels
plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
 
############
## Percent
############
 
totals = [i+j+k for i,j,k in zip(blue_data, red_data, green_data)]
blue_rel = [i / j * 100 for  i,j in zip(blue_data, totals)]
red_rel = [i / j * 100 for  i,j in zip(red_data, totals)]
green_rel = [i / j * 100 for  i,j in zip(green_data, totals)]
 
ax2.bar(bar_l, blue_rel,
        label='blue data', alpha=0.5, color='b', width=bar_width
        )
ax2.bar(bar_l, red_rel,
        bottom=blue_rel, label='red data', alpha=0.5, color='r', width=bar_width
        )
ax2.bar(bar_l, green_rel,
        bottom=[i+j for i,j in zip(blue_rel, red_rel)],
        label='green data', alpha=0.5, color='g', width=bar_width
        )
 
plt.sca(ax2)
plt.xticks(tick_pos, ['category 1', 'category 2', 'category 3'])
ax2.set_ylabel("Percentage")
ax2.set_xlabel("")
 
plt.xlim([min(tick_pos)-bar_width, max(tick_pos)+bar_width])
plt.grid()
 
# rotate axis labels
plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
 
plt.show()

image.png

  • 带标签的条形图1
from matplotlib import pyplot as plt
import numpy as np
 
data = range(200, 225, 5)
 
bar_labels = ['a', 'b', 'c', 'd', 'e']
 
fig = plt.figure(figsize=(10,8))
 
# 画图
y_pos = np.arange(len(data))
plt.yticks(y_pos, bar_labels, fontsize=16)
bars = plt.barh(y_pos, data,
         align='center', alpha=0.4, color='g')
 
# 注释
 
for b,d in zip(bars, data):
    plt.text(b.get_width() + b.get_width()*0.08, b.get_y() + b.get_height()/2,
        '{0:.2%}'.format(d/min(data)),
        ha='center', va='bottom', fontsize=12)
 
plt.xlabel('X axis label', fontsize=14)
plt.ylabel('Y axis label', fontsize=14)
t = plt.title('Bar plot with plot labels/text', fontsize=18)
plt.ylim([-1,len(data)+0.5])
plt.vlines(min(data), -1, len(data)+0.5, linestyles='dashed')
plt.grid()
 
plt.show()

image.png

  • 带标签的条形图2
import matplotlib.pyplot as plt
 
# 输入数据
mean_values = [1, 2, 3]
bar_labels = ['bar 1', 'bar 2', 'bar 3']
 
# 画条
x_pos = list(range(len(bar_labels)))
rects = plt.bar(x_pos, mean_values, align='center', alpha=0.5)
 
# 标签
def autolabel(rects):
    for ii,rect in enumerate(rects):
        height = rect.get_height()
        plt.text(rect.get_x()+rect.get_width()/2., 1.02*height, '%s'% (mean_values[ii]),
            ha='center', va='bottom')
autolabel(rects)
 
 
 
# 设置y轴高度
max_y = max(zip(mean_values, variance)) # returns a tuple, here: (3, 5)
plt.ylim([0, (max_y[0] + max_y[1]) * 1.1])
 
# 设置标题
plt.ylabel('variable y')
plt.xticks(x_pos, bar_labels)
plt.title('Bar plot with labels')
 
plt.show()
#plt.savefig('./my_plot.png')

image.png

  • 带颜色色差的条形图
import matplotlib.pyplot as plt
import matplotlib.colors as col
import matplotlib.cm as cm
 
# 输入数据
mean_values = range(10,18)
x_pos = range(len(mean_values))
 
 
# 创建 colormap
cmap1 = cm.ScalarMappable(col.Normalize(min(mean_values), max(mean_values), cm.hot))
cmap2 = cm.ScalarMappable(col.Normalize(0, 20, cm.hot))
 
# 画条
plt.subplot(121)
plt.bar(x_pos, mean_values, align='center', alpha=0.5, color=cmap1.to_rgba(mean_values))
plt.ylim(0, max(mean_values) * 1.1)
 
plt.subplot(122)
plt.bar(x_pos, mean_values, align='center', alpha=0.5, color=cmap2.to_rgba(mean_values))
plt.ylim(0, max(mean_values) * 1.1)
 
plt.show()

image.png

  • 带填充模式的条形图
import matplotlib.pyplot as plt
 
patterns = ('-', '+', 'x', '\', '*', 'o', 'O', '.')
 
fig = plt.gca()
 
# 输入数据
mean_values = range(1, len(patterns)+1)
 
# 画条
x_pos = list(range(len(mean_values)))
bars = plt.bar(x_pos,
               mean_values,
               align='center',
               color='white',
               )
 
# 设置填充模式
for bar, pattern in zip(bars, patterns):
     bar.set_hatch(pattern)
 
 
# 设置标签
fig.axes.get_yaxis().set_visible(False)
plt.ylim([0, max(mean_values) * 1.1])
plt.xticks(x_pos, patterns)
 
plt.show()

image.png

来源:http://blog.topspeedsnail.com/archives/724#more-724

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

[519]matplotlib(三) 的相关文章

  • kali渗透--msf简单使用

    使用MSF Metasploit 利用MS12 020 RDP远程代码执行漏洞 实验环境准备 1 一台 winXP 作为受害者 最好拍摄好一个快照 IP 10 1 1 2 2 kali 作为攻击者 IP 10 1 1 1 3 将攻击者和受害

随机推荐

  • 常用命令图解 & & git 错误 fatal: Not a valid object name: ‘master‘.

    亲测可用 若有疑问请私信 常用命令图解 转自Git 常用命令详解 二 阳光岛主的博客 CSDN博客 git命令 Git 是一个很强大的分布式版本管理工具 它不但适用于管理大型开源软件的源代码 如 linux kernel 管理私人的文档和源
  • Python画各种爱心

    目录 一行代码画爱心 拆解 输出 I U 填充型 动态画红心 桃心 线性 立体红心 玫瑰 树 一行代码画爱心 print n join join Love x y len Love if x 0 05 2 y 0 1 2 1 3 x 0 0
  • 学科竞赛管理系统服务器错误,学科竞赛管理系统

    系统功能模块如下 1 平台首页 整个平台首页分为政策文件 竞赛列表 在线报名 成果展示 通知公告 新闻中心 联系方式 系统登录 下载中心 快速导航等功能模块 所有模块内容全部支持系统后台进行添加 编辑 删除等操作 2 竞赛管理 1 竞赛项目
  • TensorRT/parsers/caffe/caffeParser/caffeParser.h源碼研讀

    TensorRT parsers caffe caffeParser caffeParser h源碼研讀 前言 TensorRT parsers caffe caffeParser caffeParser h delete this std
  • mysql中的枚举enum_mysql中枚举类型之enum详解

    enum类型就是我们常说的枚举类型 它的取值范围需要在创建表时通过枚举方式 一个个的列出来 显式指定 对1至255个成员的枚举需要1个字节存储 对于255至65535个成员 需要2个字节存储 最多允许有65535个成员 先通过sql语句创建
  • Latex 算法Algorithm

    在计算机科学当中 论文当中经常需要排版算法 相信大家在读论文中也看见了很多排版精美的算法 本文就通过示例来简要介绍一下 algorithms 束的用法 该束主要提供了两个宏包 包含两种进行算法排版的环境 algorithm 和 algori
  • java base64转文件_java之文件与base64字符之间的相互转换

    package cn xuanyuan util import java io File import java io FileInputStream import java io FileOutputStream import sun m
  • 大数据 机器学习 分类算法_13种用于数据科学的机器学习分类算法及其代码

    大数据 机器学习 分类算法 The roundup of most common classification algorithms along with their python and r code 吨 他的Roundup与他们的Pyt
  • WSL安装JDK8

    2019独角兽企业重金招聘Python工程师标准 gt gt gt 下载地址 JDK URL https www oracle com technetwork java javase downloads jdk8 downloads 213
  • 压缩感知进阶——有关稀疏矩阵

    上一篇 初识压缩感知Compressive Sensing 中我们已经讲过了压缩感知的作用和基本想法 涉及的领域 本文通过学习陶哲轩对compressive sensing CS 的课程 对压缩感知做进一步理解 针对其原理做出讲解 本文较为
  • poi 导出excel工具类包含导出内容为List<Map<String,Object>>,List<List<Object>>

    导入jar
  • JVM结构和GC垃圾回收

    JVM知识 一 JVM结构 1 类加载子系统 用于将class字节码文件加载到JVM中 2 JVM运行时数据区 又被称为内存结构 线程共享数据 1 堆 放对象的地方 2 方法区 元空间 存储类的模板信息 xxx class的模板信息 堆中同
  • C++ 大话设计之《备忘录模式》(优缺点,设计原理,常用场景)

    备忘录模式是一种行为型模式 优点 备忘录模式的主要优点是提供了一种可以恢复状态的机制 当用户需要时能够比较方便地将数据恢复到某个历史的状态 它实现了内部状态的封装 除了创建它的发起人之外 其他对象都不能够访问这些状态信息 此外 它简化了发起
  • 【Tableau小练习】销售数据的分析思路

    概要 电商数据分析案例 分析思路 从整体到局部 关键指标 销售额 通过宏观的数据 找出最明显的数据趋势 结合品牌自身的营销活动 再下钻挖掘详细的价值信息 成果展示 Tableau Public https public tableau co
  • 17_Nginx_PostRead阶段

    文章目录 post read 阶段 获取真实的用户IP地址 基于变量使用用户ip realip 模块 realip 模块的指令 post read 阶段 获取真实的用户IP地址 tcp 四元组 src ip src port dst ip
  • 本地镜像如何推送到docker 仓库

    要将本地镜像推送到Docker仓库 需要按照以下步骤操作 1 首先 使用 docker login 命令登录到Docker仓库 输入用户名和密码进行身份验证 2 然后 使用 docker tag 命令为本地镜像添加标签 语法为 docker
  • 39_MoreThanHalfNumber 数组中超过一半的元素

    数组中有一个数字出现的次数超过数组长度的一半 请找出这个数字 你可以假设数组是非空的 并且给定的数组总是存在多数元素 示例 1 输入 1 2 3 2 2 2 5 4 2 输出 2 1 利用hashmap统计数组中元素出现的次数 如果次数大于
  • Elasticsearch 搜索数组字段

    我的个人博客 逐步前行STEP 1 搜索 数组字段 tags 中同时存在元素 str a str b query bool filter term tags str a term tags str b 2 搜索 数组字段 tags 中存在元
  • vue怎么vw布局好用_vue2.x使用响应式vw布局(px自动转为vw)

    浏览器支持一览 1 依赖包引入 yarn add postcss px to viewport opt postcss viewport units cssnano cssnano preset advanced dev 2 更改项目根目录
  • [519]matplotlib(三)

    带误差线的条形图 import matplotlib pyplot as plt 输入数据 mean values 1 2 3 variance 0 2 0 4 0 5 bar labels bar 1 bar 2 bar 3 绘制图形 x