基于Python绘制子图及子图刻度的变换等的问题


Posted in Python onMay 23, 2021

1、涉及到图的对比会用到子图形式展示

先看看效果

基于Python绘制子图及子图刻度的变换等的问题

2、绘制代码如下

accuracy_alexnet_clef = [78.05, 78.43, 78.65, 78.61, 78.69]
accuracy_resnet_clef  = [84.56, 84.84, 85.07, 85.01, 85.13]
accuracy_alexnet_office10 = [87.30, 87.57, 87.78, 87.72, 87.50]
accuracy_resnet_office10  = [96.31, 96.35, 96.62, 96.43, 96.15]
orders = ['2', '3', '5', '10', '20']
names = ['alexnet', 'resnet']
# 创建两幅子图
f, ax = plt.subplots(2,1,figsize=(6, 8))
# 第一根柱子偏移坐标
x = [i for i in range(len(orders))]
# 第二根柱子偏移坐标
x1 = [i + 0.35 for i in range(len(orders))]
# 两幅子图之间的间距
plt.subplots_adjust(wspace =0, hspace =0.4)
# 选择第一幅图
figure_1 = ax[0]
# 设置x轴偏移和标签
figure_1.set_xticks([i+0.15 for i in x])
figure_1.set_xticklabels(orders)
# 设置y轴的范围
figure_1.set_ylim(bottom=77,top=86)
# 绘制柱状图,x表示x轴内容,accuracy_alexnet_clef表示y轴的内容,alpha表示透明度,width表示柱子宽度
# label表示图列
figure_1.bar(x, accuracy_alexnet_clef, alpha=0.7, width = 0.35, facecolor = '#4c72b0', label='Alexnet')
figure_1.bar(x1, accuracy_resnet_clef, alpha=0.7, width = 0.35, facecolor = '#dd8452', label='Resnet')
figure_1.set_ylabel('Accuracy%') # 设置y轴的标签
figure_1.set_xlabel('Order') # 设置x轴的名称
figure_1.set_title('Alexnet') # 设置图一标题名称
figure_1.legend() # 显示图一的图例
# 选择第二幅图
figure_2 = ax[1]
figure_1.set_xticks([i+0.15 for i in x])
figure_1.set_xticklabels(orders)
figure_2.set_ylim(bottom=77,top=100)
figure_2.bar(x, accuracy_alexnet_office10,alpha=0.7,width = 0.35,facecolor = '#c44e52', label='Alexnet')
figure_2.bar(x1, accuracy_resnet_office10,alpha=0.7,width = 0.35,facecolor = '#5f9e6e', label='Alexnet')
# figure_2.bar(orders, accuracy_resnet_clef,alpha=0.7,width = 0.35,facecolor = '#dd8452')
figure_2.set_ylabel('Accuracy%')
figure_2.set_xlabel('Order')
figure_2.set_title('Resnet')
figure_2.legend()
f.suptitle('ImageCLEF_DA') # 设置总标题
plt.show()

补充:python使用matplotlib在一个图形中绘制多个子图以及一个子图中绘制多条动态折线问题

在讲解绘制多个子图之前先简单了解一下使用matplotlib绘制一个图,导入绘图所需库matplotlib并创建一个等间隔的列表x,将[0,2*pi]等分为50等份,绘制函数sin(x)。当没有给定x轴数值时,默认以下标作为x的值,如果x值确定,则绘图时写为plt.plot(x,y) 。

如若想要绘制一个图时写入标签,则写为plt.plot(x,y,label="figure1")。

from numpy import *
import matplotlib.pyplot as plt 
x = linspace(0, 2 * pi, 50)
plt.plot(sin(x))
plt.xlabel('x-label')
plt.ylabel('y-label', fontsize='large')
plt.title('title')

基于Python绘制子图及子图刻度的变换等的问题

以下先将整体代码插入,再分布讲解:

import numpy as np
import matplotlib.pyplot as plt 
from matplotlib.ticker import MultipleLocator, FormatStrFormatter 
def minmax_value(list1):
    minvalue=min(list1)
    maxvalue=max(list1)
    return minvalue,maxvalue
plt.figure(figsize=(16,14),dpi=98)
xmajorLocator = MultipleLocator(1) #将x主刻度标签设置为1的倍数
plt.rcParams['font.sans-serif']=['SimHei']  
plt.rcParams['axes.unicode_minus'] = False
p1 = plt.subplot(121)
p2 = plt.subplot(122)
#图中展示点的数量
pointcount=5
x=[i for i in range(20)]
print(x)
y1=[i**2 for i in range(20)]
y2=[i*4 for i in range(20)]
y3=[i*3+2 for i in range(20)]
y4=[i*4 for i in range(20)]
for i in range(len(x)-1):
    if i<pointcount:
        minx,maxx=minmax_value(x[:pointcount])
        minx,maxx=minmax_value(x[:pointcount])
        minyA,maxyA=minmax_value(y1[:pointcount])
        minyB,maxyB=minmax_value(y2[:pointcount])
        
        maxy1=max(maxyA,maxyB)
        miny1=min(minyA,minyB)
        p1.axis([minx,maxx,miny1,maxy1])
        p1.grid(True)
        A,=p1.plot(x[:pointcount],y1[:pointcount],"g-")
        B,=p1.plot(x[:pointcount],y2[:pointcount],"b-")
        #设置主刻度标签的位置,标签文本的格式
        p1.xaxis.set_major_locator(xmajorLocator)
        legend=p1.legend(handles=[A,B],labels=["图1","图2"])    
        
        
        minx,maxx=minmax_value(x[:pointcount])
        minx,maxx=minmax_value(x[:pointcount])
        minyA,maxyA=minmax_value(y3[:pointcount])
        minyB,maxyB=minmax_value(y4[:pointcount])
        
        maxy1=max(maxyA,maxyB)
        miny1=min(minyA,minyB)
        p2.axis([minx,maxx,miny1,maxy1])
        p2.grid(True)
        A,=p2.plot(x[:pointcount],y3[:pointcount],"r-")
        B,=p2.plot(x[:pointcount],y4[:pointcount],"y-")
        #设置主刻度标签的位置,标签文本的格式
        p2.xaxis.set_major_locator(xmajorLocator)
        legend=p2.legend(handles=[A,B],labels=["图3","图4"])  
    elif i>=pointcount:
        minx,maxx=minmax_value(x[i-pointcount:i])
        minx,maxx=minmax_value(x[i-pointcount:i])
        minyA,maxyA=minmax_value(y1[i-pointcount:i])
        minyB,maxyB=minmax_value(y2[i-pointcount:i])
        
        maxy1=max(maxyA,maxyB)
        miny1=min(minyA,minyB)
        p1.axis([minx,maxx,miny1,maxy1])
        p1.grid(True)
        A,=p1.plot(x[i-pointcount:i],y1[i-pointcount:i],"g-")
        B,=p1.plot(x[i-pointcount:i],y2[i-pointcount:i],"b-")
        #设置主刻度标签的位置,标签文本的格式
        p1.xaxis.set_major_locator(xmajorLocator)
        legend=p1.legend(handles=[A,B],labels=["图1","图2"])
        minx,maxx=minmax_value(x[i-pointcount:i])
        minx,maxx=minmax_value(x[i-pointcount:i])
        minyA,maxyA=minmax_value(y3[i-pointcount:i])
        minyB,maxyB=minmax_value(y4[i-pointcount:i])
        
        maxy1=max(maxyA,maxyB)
        miny1=min(minyA,minyB)
        p2.axis([minx,maxx,miny1,maxy1])
        p2.grid(True)
        A,=p2.plot(x[i-pointcount:i],y3[i-pointcount:i],"r-")
        B,=p2.plot(x[i-pointcount:i],y4[i-pointcount:i],"y-")
        #设置主刻度标签的位置,标签文本的格式
        p2.xaxis.set_major_locator(xmajorLocator)
        legend=p2.legend(handles=[A,B],labels=["图3","图4"])
    p1.set_xlabel("横轴属性名一",fontsize=14)
    p1.set_ylabel("纵轴属性名一",fontsize=14)
    p1.set_title("主题一",fontsize=18)
    
    p2.set_xlabel("横轴属性名二",fontsize=14)
    p2.set_ylabel("纵轴属性名二",fontsize=14)
    p2.set_title("主题二",fontsize=18)
    plt.pause(0.3)
    plt.tight_layout(pad=4, w_pad=4.0, h_pad=3.0)

运行结果为:

基于Python绘制子图及子图刻度的变换等的问题

1、导入库

import numpy as np
import matplotlib.pyplot as plt 
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

2、由于绘图过程中多次使用获取最大最小值,将获取最大最小值写入函数,后面直接调用函数即可。

def minmax_value(list1):
    minvalue=min(list1)
    maxvalue=max(list1)
    return minvalue,maxvalue

3、

(1)创建自定义图像,并设置figured的长和宽以及dpi参数指定绘图对象的分辨率;

(2)设置x轴刻度的间隔;

(3)对本次绘图中的字体进行设置;

(4)在matplotlib下,一个figure对象可以包含多个子图(Axes),使用subplot()快速绘制。

plt.figure(figsize=(16,14),dpi=98)xmajorLocator = MultipleLocator(1)
plt.rcParams['font.sans-serif']=['SimHei']  plt.rcParams['axes.unicode_minus'] = False
 
p1 = plt.subplot(121)p2 = plt.subplot(122)

4、当数据量过多时,对数据一次性展示不能够达到对数据内部信息的解读。本例采用一次展示其中一部分数据,并动态的更新图片,于此同时,动态更新横纵坐标轴的取值范围。下面代码首先设置了每次展示点的数量,并获取了主题一中的所有数据值。根据x取值范围和值域y获取当前绘图过程中的横纵坐标取值范围,最后根据x,y的值进行绘图。

下面将先在一个子图上显示两条静态折现。当使用动态的折线图时,只需动态更新数据和横纵坐标的取值范围。总体代码中已经写出,下面不再赘述。

#图中展示点的数量
pointcount=5
x=[i for i in range(20)]
y1=[i**2 for i in range(20)]
y2=[i*4 for i in range(20)]
minx,maxx=minmax_value(x[:pointcount])
minyA,maxyA=minmax_value(y1[:pointcount])
minyB,maxyB=minmax_value(y2[:pointcount])
        
maxy1=max(maxyA,maxyB)
miny1=min(minyA,minyB)
p1.axis([minx,maxx,miny1,maxy1])
p1.grid(True)#绘图过程中出现的网格设置
A,=p1.plot(x[:pointcount],y1[:pointcount],"g-")
B,=p1.plot(x[:pointcount],y2[:pointcount],"b-")#设置主刻度标签的位置,标签文本的格式p1.xaxis.set_major_locator(xmajorLocator)legend=p1.legend(handles=[A,B],labels=["图1","图2"])

结果如下所示:

基于Python绘制子图及子图刻度的变换等的问题

5、设置边界,不设置边界经常会因为横纵轴的字体太大等其他原因导致横纵轴或者标题只能显示其中一部分。

plt.tight_layout(pad=4, w_pad=4.0, h_pad=3.0)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python ORM框架SQLAlchemy学习笔记之安装和简单查询实例
Jun 10 Python
python中循环语句while用法实例
May 16 Python
Python网络爬虫项目:内容提取器的定义
Oct 25 Python
Python 记录日志的灵活性和可配置性介绍
Feb 27 Python
python取数作为临时极大值(极小值)的方法
Oct 15 Python
numpy 对矩阵中Nan的处理:采用平均值的方法
Oct 30 Python
正确理解Python中if __name__ == '__main__'
Jan 24 Python
python使用PyQt5的简单方法
Feb 27 Python
python程序运行进程、使用时间、剩余时间显示功能的实现代码
Jul 11 Python
Python 200行代码实现一个滑动验证码过程详解
Jul 11 Python
python开发实例之python使用Websocket库开发简单聊天工具实例详解(python+Websocket+JS)
Mar 18 Python
简单了解Python多态与属性运行原理
Jun 15 Python
聊聊pytorch测试的时候为何要加上model.eval()
May 23 #Python
PyTorch 如何自动计算梯度
May 23 #Python
解决numpy和torch数据类型转化的问题
May 23 #Python
Python 用户输入和while循环的操作
May 23 #Python
解决Tkinter中button按钮未按却主动执行command函数的问题
May 23 #Python
python tkinter Entry控件的焦点移动操作
May 22 #Python
python3.7.2 tkinter entry框限定输入数字的操作
May 22 #Python
You might like
浏览器预览PHP文件时顶部出现空白影响布局分析原因及解决办法
2013/01/11 PHP
php实现可逆加密的方法
2015/08/11 PHP
php提高网站效率的技巧
2015/09/29 PHP
php源码之将图片转化为data/base64数据流实例详解
2016/11/27 PHP
PHP使用xpath解析XML的方法详解
2017/05/20 PHP
laravel框架实现为 Blade 模板引擎添加新文件扩展名操作示例
2020/01/25 PHP
通过Jscript中@cc_on 语句识别IE浏览器及版本的代码
2011/05/07 Javascript
IE6/7/8/9不支持exec的简写方式
2011/05/25 Javascript
利用JS解决ie6不支持max-width,max-height问题的方法
2014/01/02 Javascript
Bootstrap每天必学之级联下拉菜单
2016/03/27 Javascript
jQuery视差滚动效果网页实现方法经验总结
2016/09/29 Javascript
jQuery  ready方法实现原理详解
2016/10/19 Javascript
react实现点击选中的li高亮的示例代码
2018/05/24 Javascript
浅谈Javascript中的对象和继承
2019/04/19 Javascript
vue实现直播间点赞飘心效果的示例代码
2019/09/20 Javascript
JavaScript oncopy事件用法实例解析
2020/05/13 Javascript
区分vue-router的hash和history模式
2020/10/03 Javascript
浅谈Vue static 静态资源路径 和 style问题
2020/11/07 Javascript
[52:09]2014 DOTA2华西杯精英邀请赛 5 25 NewBee VS DK第二场
2014/05/26 DOTA
[12:29]2018国际邀请赛 开幕秀
2018/08/22 DOTA
使用python加密自己的密码
2015/08/04 Python
python socket网络编程之粘包问题详解
2018/04/28 Python
Python高级特性 切片 迭代解析
2019/08/23 Python
python实现实时视频流播放代码实例
2020/01/11 Python
HTML5 canvas基本绘图之图形变换
2016/06/27 HTML / CSS
日本食品网上商店:JaponShop.com
2017/11/28 全球购物
全球领先的在线cosplay服装商店:RoleCosplay
2020/01/18 全球购物
自主招生自荐书
2013/11/29 职场文书
商务英语应届生自我鉴定
2013/12/08 职场文书
技术负责人任命书
2014/06/05 职场文书
个人股份转让协议书范本
2014/10/26 职场文书
2014年售后服务工作总结
2014/11/18 职场文书
国家助学贷款承诺书
2015/04/30 职场文书
小学学习委员竞选稿
2015/11/20 职场文书
医学生自荐信范文(2016精选篇)
2016/01/28 职场文书
2016优秀护士先进个人事迹材料
2016/02/25 职场文书