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\times 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 product def 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+1
for 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的更多相关文章

  1. matplotlib 进阶之origin and extent in imshow

    目录 显示的extent Explicit extent and axes limits matplotlib教程学习笔记 import numpy as np import matplotlib.p ...

  2. matplotlib 进阶之Tight Layout guide

    目录 简单的例子 Use with GridSpec Legend and Annotations Use with AxesGrid1 Colorbar 函数链接 matplotlib教程学习笔记 ...

  3. matplotlib 进阶之Constrained Layout Guide

    目录 简单的例子 Colorbars Suptitle Legends Padding and Spacing spacing with colobars rcParams Use with Grid ...

  4. 【python】matplotlib进阶

    参考文章:https://liam0205.me/2014/09/11/matplotlib-tutorial-zh-cn/ 几个重要对象:图像.子图.坐标轴.记号 figure:图像, subplo ...

  5. matplotlib 进阶之Legend guide

    目录 matplotlib.pyplot.legend 方法1自动检测 方法2为现有的Artist添加 方3显示添加图例 控制图例的输入 为一类Artist设置图例 Legend 的位置 loc, b ...

  6. matplotlib 进阶之Artist tutorial(如何操作Atrist和定制)

    目录 基本 plt.figure() fig.add_axes() ax.lines set_xlabel 一个完整的例子 定制你的对象 obj.set(alpha=0.5, zorder=2), o ...

  7. matplotlib常用操作2

    关于matplotlib学习还是强烈建议常去官方http://matplotlib.org/contents.html里查一查各种用法和toturial等. 下面是jupyter notebook代码 ...

  8. Python第三方库matplotlib(2D绘图库)入门与进阶

    Matplotlib 一 简介: 二 相关文档: 三 入门与进阶案例 1- 简单图形绘制 2- figure的简单使用 3- 设置坐标轴 4- 设置legend图例 5- 添加注解和绘制点以及在图形上 ...

  9. matplotlib使用GridSpec调整子图位置大小 (非对称的子图)

    用matplotlib.pyplot的subplots命令可以很方便的画对称的子图,但是如果要画非对称的子图(如下)就需要用GridSpec命令来控制子图的位置和大小: 而上图的结构可以用一下两种方式 ...

随机推荐

  1. ORACLE profile含义,修改,新增

    profiles文件是口令和资源限制的配置集合,包括CPU的时间.I/O的使用.空闲时间.连接时间.并发会话数量.密码策略等对于资源的使用profile可以做到控制会话级别或语句调用级别.oracle ...

  2. 11-如何通过newman生成不同类型的测试报告

    postman生成测试报告需要一个插件:newman ,并且这个插件需要先安装 . 安装步骤: 安装nodejs: newman是由nodejs开发,所以要先安装它的运行环境,下载地址:http:// ...

  3. 【Linux】【Services】【SaaS】Docker+kubernetes(1. 基础概念与架构图)

    1.简介 1.1.  背景:公司正在进行敏捷开发环境的搭建,以取代传统的架构,好处大大的,我就不赘述了.公司原来负责这个项目的同事要转组,我只好交给另外同事继续,但是为了防止同样的事情,我也需要深入了 ...

  4. 实现new Date(), 获取当前时间戳

    JS 获取时间戳: 我相信大家找了很久了吧! 希望我写的这个对您有些帮助哦~ 大家是不是以为时间戳是关于时间的,都去 new Date() 里面找方法了啊,我来告诉你们正确的吧 其实大家用 JS 里的 ...

  5. spring的注解AOP配置

    package com.hope.service.impl;import com.hope.service.IAccountService;import org.aspectj.lang.annota ...

  6. JVM堆空间结构及常用的jvm内存分析命令和工具

    jdk8之前的运行时数据区域 程序计数器 是一块较小的内存空间,它可以看做是当前线程所执行的字节码的行号指示器.每个线程都有一个独立的程序计数器,这类内存区域为"线程私有",此内存 ...

  7. 南京邮电大学CTF密码学之MD5-golang与php代码实现

    题目内容:这里有一段丢失的md5密文 e9032???da???08????911513?0???a2 要求你还原出他并且加上nctf{}提交 已知线索 明文为: TASC?O3RJMV?WDJKX? ...

  8. windows 显示引用账户已被锁定,且可能无法登录

    今天遇到一个比较尴尬的事情,清理笔记本键盘时,在锁屏界面多次碰到enter键,在登录界面被锁定无法登录. 一开始慌了,因为没遇到过这样的问题.百度一看方法不少,便开始尝试, 有的说是重启进入安全模式, ...

  9. JDK各版本新增的主要特性总结

    JDK1.5新特性: 1.自动装箱与拆箱: 2.枚举 3.静态导入,如:import staticjava.lang.System.out 4.可变参数(Varargs) 5.内省(Introspec ...

  10. BJD4th pwn pi

    没记错的话,比赛那天正好是圣诞节,就只看了这一道pwn题,我还没做出来.我太菜了. 有一说一,ida换成7.5版本之后,一些去掉符号表的函数也能被识别出来了,ida更好用了呢. 题目程序分为两块,先看 ...