matplotlib 进阶之Customizing Figure Layouts Using GridSpec and Other Functions

本文主要是介绍matplotlib 进阶之Customizing Figure Layouts Using GridSpec and Other Functions,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

    • 对Gridspec的一些精细的调整
    • 利用SubplotSpec
      • fig.add_grdispec; gs.subgridspec
    • 一个利用Subplotspec的复杂例子
    • 函数链接

matplotlib教程学习笔记

如何创建网格形式的axes的组合呢:

  1. subplots()
  2. GridSpec
  3. SubplotSpec
  4. subplot2grid()
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

第一个例子是利用subplots()和gridspec来创建一个 2 × 2 2\times 2 2×2的网格
首先利用subplots()是很容易做到这一点的:

fig1, fi_axes = plt.subplots(ncols=2, nrows=2, constrained_layout=True) #constrain_layout参数似乎是控制是否会重叠的

在这里插入图片描述

使用gridspec需要先创建一个fig对象,再创建Gridspec对象,然后将实例传入add_subplot(),gridspec的使用习惯和numpy数组是相当的

fig2 = plt.figure(constrained_layout=True)
spec2 = gridspec.GridSpec(ncols=2, nrows=2, figure=fig2)
f2_ax1 = fig2.add_subplot(spec2[0, 0])
f2_ax2 = fig2.add_subplot(spec2[0, 1])
f2_ax3 = fig2.add_subplot(spec2[1, 0])
f2_ax4 = fig2.add_subplot(spec2[1, 1])

在这里插入图片描述

gridspec有什么厉害的地方呢,我们可以通过索引和切片操作,使得某些axes占据多个格子

fig3 = plt.figure(constrained_layout=True)
gs = fig3.add_gridspec(3, 3)
f3_ax1 = fig3.add_subplot(gs[0, :])
f3_ax1.set_title('gs[0, :]')
f3_ax2 = fig3.add_subplot(gs[1, :-1])
f3_ax2.set_title('gs[1, :-1]')
f3_ax3 = fig3.add_subplot(gs[1:, -1])
f3_ax3.set_title('gs[1:, -1]')
f3_ax4 = fig3.add_subplot(gs[-1, 0])
f3_ax4.set_title('gs[-1, 0]')
f3_ax5 = fig3.add_subplot(gs[-1, -2])
f3_ax5.set_title('gs[-1, -2]');

在这里插入图片描述

fig4 = plt.figure(constrained_layout=True)
spec4 = fig4.add_gridspec(ncols=2, nrows=2)
anno_opts = dict(xy=(0.3, 0.3), xycoords='axes fraction',va='center', ha='center')f4_ax1 = fig4.add_subplot(spec4[0, 0])
f4_ax1.annotate('GridSpec[0, 0]', **anno_opts)
fig4.add_subplot(spec4[0, 1]).annotate('GridSpec[0, 1:]', **anno_opts)
fig4.add_subplot(spec4[1, 0]).annotate('GridSpec[1:, 0]', **anno_opts)
fig4.add_subplot(spec4[1, 1]).annotate('GridSpec[1:, 1:]', **anno_opts);

在这里插入图片描述

另外的,width_ratios和height_ratios参数,参数需要传入一个装有数字,比如[2, 4, 8]和
[1, 2, 4],不过这俩个表示的含义是一样的,因为参数关系的他们之间的比例:
2:4:8与1:2:4是一致的。

fig5 = plt.figure(constrained_layout=True)
widths = [2, 3, 1.5]
heights = [1, 3, 2]
spec5 = fig5.add_gridspec(ncols=3, nrows=3, width_ratios=widths,height_ratios=heights)
for row in range(3):for col in range(3):ax = fig5.add_subplot(spec5[row, col])label = 'Width: {}\nHeight: {}'.format(widths[col], heights[row])ax.annotate(label, (0.1, 0.5), xycoords='axes fraction', va='center')

在这里插入图片描述

事实上,width_ratio参数和height_ratio参数对于subplots()是十分便利的一个工具,subplots()有一个gridspec_kw参数,事实上,借此我们可以将传入gridspec的参数传入subplots(),具体形式如下:

gs_kw = dict(width_ratios=widths, height_ratios=heights)
fig6, f6_axes = plt.subplots(ncols=3, nrows=3, constrained_layout=True,gridspec_kw=gs_kw)
for r, row in enumerate(f6_axes):for c, ax in enumerate(row):label = 'Width: {}\nHeight: {}'.format(widths[c], heights[r])ax.annotate(label, (0.1, 0.5), xycoords='axes fraction', va='center')

在这里插入图片描述

subplots和gridspec二者可以结合,比如,我们可以通过subplots先创建大部分的axes,再利用gridspec组合某些部分,当然,这可能需要利用到
get_gridspec方法和remove方法

fig7, f7_axs = plt.subplots(ncols=3, nrows=3)
gs = f7_axs[1, 2].get_gridspec()
# remove the underlying axes
for ax in f7_axs[1:, -1]:ax.remove()
axbig = fig7.add_subplot(gs[1:, -1])
axbig.annotate('Big Axes \nGridSpec[1:, -1]', (0.1, 0.5),xycoords='axes fraction', va='center')fig7.tight_layout();

在这里插入图片描述

对Gridspec的一些精细的调整

当gridspec被显示使用的时候,我们可以通过一些参数来进行细微的调整,注意这个选择与constrained_layout或者figure.tight_layout是有冲突的

left : axes左边缘距离画板左侧的距离

right: axes右边缘距离画板左侧的距离

top : axes上边缘距离画板下侧的距离

bottom : axes下边缘距离画板下侧的距离

hspace: 预留给subplots之间的高度的距离

wspace: 预留给subplots之间的宽度的距离

fig8 = plt.figure(constrained_layout=False) #注意设置为False否则会冲突
gs1 = fig8.add_gridspec(nrows=3, ncols=3, right=0.88, wspace=0.05)
f8_ax1 = fig8.add_subplot(gs1[:-1, :])
f8_ax2 = fig8.add_subplot(gs1[-1, :-1])
f8_ax3 = fig8.add_subplot(gs1[-1, -1])

在这里插入图片描述
这些细微的调整只对由gridspec创建的格子有效

fig9 = plt.figure(constrained_layout=False)
gs1 = fig9.add_gridspec(nrows=3, ncols=3, left=0.05, right=0.48,wspace=0.05)
f9_ax1 = fig9.add_subplot(gs1[:-1, :])
f9_ax2 = fig9.add_subplot(gs1[-1, :-1])
f9_ax3 = fig9.add_subplot(gs1[-1, -1])gs2 = fig9.add_gridspec(nrows=3, ncols=3, left=0.55, right=0.98,hspace=0.05)
f9_ax4 = fig9.add_subplot(gs2[:, :-1])
f9_ax5 = fig9.add_subplot(gs2[:-1, -1])
f9_ax6 = fig9.add_subplot(gs2[-1, -1])

在这里插入图片描述

利用SubplotSpec

fig.add_grdispec; gs.subgridspec

fig10 = plt.figure(constrained_layout=True)
gs0 = fig10.add_gridspec(1, 2)gs00 = gs0[0].subgridspec(2, 3)
gs01 = gs0[1].subgridspec(3, 2)for a in range(2):for b in range(3):fig10.add_subplot(gs00[a, b])fig10.add_subplot(gs01[b, a])

在这里插入图片描述

一个利用Subplotspec的复杂例子

import numpy as np
from itertools import productdef squiggle_xy(a, b, c, d, i=np.arange(0.0, 2*np.pi, 0.05)):return np.sin(i*a)*np.cos(i*b), np.sin(i*c)*np.cos(i*d)fig11 = plt.figure(figsize=(8, 8), constrained_layout=False)# gridspec inside gridspec
outer_grid = fig11.add_gridspec(4, 4, wspace=0.0, hspace=0.0) #4 x 4个大格子for i in range(16):inner_grid = outer_grid[i].subgridspec(3, 3, wspace=0.0, hspace=0.0) #3 x 3个小格子a, b = int(i/4)+1, i % 4+1for j, (c, d) in enumerate(product(range(1, 4), repeat=2)):ax = plt.Subplot(fig11, inner_grid[j])ax.plot(*squiggle_xy(a, b, c, d))ax.set_xticks([])ax.set_yticks([])fig11.add_subplot(ax)all_axes = fig11.get_axes()# show only the outside spines
# 之显示每个大格子外面的边框,小格子的边框就不显示
for ax in all_axes:for sp in ax.spines.values():sp.set_visible(False)if ax.is_first_row():ax.spines['top'].set_visible(True)if ax.is_last_row():ax.spines['bottom'].set_visible(True)if ax.is_first_col():ax.spines['left'].set_visible(True)if ax.is_last_col():ax.spines['right'].set_visible(True)plt.show()

在这里插入图片描述

函数链接

subplots
GridSpec
Subplotsepc
subplot2grid()
subplots.adjust()

这篇关于matplotlib 进阶之Customizing Figure Layouts Using GridSpec and Other Functions的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/291134

相关文章

UnityException: Gizmo drawing functions can only be used in OnDrawGizmos and OnDrawGizmosSelected.

You don't have to call OnDrawGizmos() From anywhere, it is a editor function to display gizmos in the scene-view and is called automatically called!! 不能在任何地方调用 OnDrawGizmos(),这个函数是自动调用的。这个函数是编辑器函数,用来

RedHat运维-Linux文本操作基础-AWK进阶

你不用整理,跟着敲一遍,有个印象,然后把它保存到本地,以后要用再去看,如果有了新东西,你自个再添加。这是我参考牛客上的shell编程专项题,只不过换成了问答的方式而已。不用背,就算是我自己亲自敲,我现在好多也记不住。 1. 输出nowcoder.txt文件第5行的内容 2. 输出nowcoder.txt文件第6行的内容 3. 输出nowcoder.txt文件第7行的内容 4. 输出nowcode

【Linux进阶】UNIX体系结构分解——操作系统,内核,shell

1.什么是操作系统? 从严格意义上说,可将操作系统定义为一种软件,它控制计算机硬件资源,提供程序运行环境。我们通常将这种软件称为内核(kerel),因为它相对较小,而且位于环境的核心。  从广义上说,操作系统包括了内核和一些其他软件,这些软件使得计算机能够发挥作用,并使计算机具有自己的特生。这里所说的其他软件包括系统实用程序(system utility)、应用程序、shell以及公用函数库等

BD错误集锦1——[Hive]ERROR StatusLogger No log4j2 configuration file found. Using default configuration:

错误描述:在使用IDEA进行jdbc方式连接到hive数据仓库时,出现以下错误:                ERROR StatusLogger No log4j2 configuration file found. 问题原因:缺少log4j2.xml文件   <?xml version="1.0" encoding="UTF-8"?><Configuration><Appender

论文阅读--Efficient Hybrid Zoom using Camera Fusion on Mobile Phones

这是谷歌影像团队 2023 年发表在 Siggraph Asia 上的一篇文章,主要介绍的是利用多摄融合的思路进行变焦。 单反相机因为卓越的硬件性能,可以非常方便的实现光学变焦。不过目前的智能手机,受制于物理空间的限制,还不能做到像单反一样的光学变焦。目前主流的智能手机,都是采用多摄的设计,一般来说一个主摄搭配一个长焦,为了实现主摄与长焦之间的变焦,目前都是采用数字变焦的方式,数字变焦相比于光学

在WinCE的C#编程中,需要静态调用C++的动态库,需要添加using System.Runtime.InteropServices

using System.Runtime.InteropServices;         [DllImport("Win32DLL.dll", EntryPoint = "WriteREG_SZToRegTCHAR")]         private static extern bool WriteREG_SZToRegTCHAR(int iFlag, string regKeyP

交通大数据分析与挖掘实训【对提供的CSV格式数据使用pandas库分析-Matplotlib库绘图】

背景: 《交通大数据分析与挖掘》实训 指    导   书  编著 二○二四年五月 一、实训目的 1、掌握python开发环境(如Anaconda)及Numpy等常见第三方库的使用; 2、熟悉Anaconda在线编程平台,学会基本的python程序编写、编译与运行程序的方法及函数语句; 3、学会导入不同格式数据文件,掌握不同类型数据的基本处理和分析思路; 4、熟练运用所学第三方库,结合相

matplotlib之常见图像种类

Matplotlib 是一个用于绘制图表和数据可视化的 Python 库。它支持多种不同类型的图形,以满足各种数据可视化需求。以下是一些 Matplotlib 支持的主要图形种类: 折线图(Line Plot): 用于显示数据随时间或其他连续变量的变化趋势。特点:能够显示数据的变化趋势,反映事物的变化情况。(变化)plt.plot() 函数用于创建折线图。  示例:

Matplotlib的原理与使用详解

文章目录 引言Matplotlib 的原理1. 底层结构2. 绘图流程3. 绘图引擎 Matplotlib 的使用1. 基本使用流程2. 自定义图表3. 保存图表 结论 引言 Matplotlib 是一个 Python 的 2D 绘图库,它提供了丰富的绘图接口,使得用户能够轻松创建各种高质量的图表。从简单的折线图、散点图到复杂的直方图、热力图等,Matplotlib 都能应对自

Python绘图:关于%matplotlib inline

%matplotlib inline 作用: 是在使用jupyter notebook 或者 jupyter qtconsole的时候,才会经常用到%matplotlib,也就是说那一份代码可能就是别人使用jupyter notebook 或者 jupyter qtconsole进行编辑的。而%matplotlib具体作用是当你调用matplotlib.pyplot的绘图函数plot()进行绘图