在pyplot模块中,与调整子图布局的函数主要为subplots_adjusttight_layout,其中subplots_adjust是修改子图间距的通用函数,tight_layout默认执行一种固定的间距配置,也可以自定义间距配置,底层原理类似于subplots_adjust函数。

subplots_adjust函数概述

subplots_adjust函数的功能为调整子图的布局参数。对于没有设置的参数保持不变,初始值由rcParams["figure.subplot.[name]"]提供。

函数的签名为matplotlib.pyplot.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

函数的参数如下:

  • left:所有子图整体相对于图像的左外边距,距离单位为图像宽度的比例(小数)。可选参数。浮点数。默认值为0.125
  • right:所有子图整体相对于图像的右外边距,距离单位为图像宽度的比例(小数)。可选参数。浮点数。默认值为0.0
  • bottom:所有子图整体相对于图像的下外边距,距离单位为图像高度的比例(小数)。可选参数。浮点数。默认值为0.11
  • top:所有子图整体相对于图像的上外边距,距离单位为图像高度的比例(小数)。可选参数。浮点数。默认值为0.88
  • wspace:子图间宽度内边距,距离单位为子图平均宽度的比例(小数)。浮点数。默认值为0.2
  • hspace:子图间高度内边距,距离单位为子图平均高度的比例(小数)。可选参数。浮点数。默认值为0.2

rcParams["figure.subplot.[name]"]的值如下:

## The figure subplot parameters.  All dimensions are a fraction of the figure width and height.
#figure.subplot.left:   0.125  # the left side of the subplots of the figure
#figure.subplot.right:  0.9    # the right side of the subplots of the figure
#figure.subplot.bottom: 0.11   # the bottom of the subplots of the figure
#figure.subplot.top:    0.88   # the top of the subplots of the figure
#figure.subplot.wspace: 0.2    # the amount of width reserved for space between subplots,# expressed as a fraction of the average axis width
#figure.subplot.hspace: 0.2    # the amount of height reserved for space between subplots,# expressed as a fraction of the average axis height

subplots_adjust函数原理

根据以下源码可知,子图间距的默认设置即rcParams["figure.subplot.[name]"],使用subplots_adjust函数调整后,间距配置保存在figure.subplotpars

pyplot.subplots_adjust()源码

def subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None,hspace=None):return gcf().subplots_adjust(left=left, bottom=bottom, right=right, top=top, wspace=wspace,hspace=hspace)

figure.Figure.subplots_adjust()源码

def subplots_adjust(self, left=None, bottom=None, right=None, top=None,wspace=None, hspace=None):if self.get_constrained_layout():self.set_constrained_layout(False)_api.warn_external("This figure was using constrained_layout, but that is ""incompatible with subplots_adjust and/or tight_layout; ""disabling constrained_layout.")self.subplotpars.update(left, bottom, right, top, wspace, hspace)for ax in self.axes:if isinstance(ax, SubplotBase):ax._set_position(ax.get_subplotspec().get_position(self))self.stale = True

figure.Figure.__init__()源码

if subplotpars is None:subplotpars = SubplotParams()self.subplotpars = subplotpars

figure.SubplotParams类源码

class SubplotParams:"""A class to hold the parameters for a subplot."""def __init__(self, left=None, bottom=None, right=None, top=None,wspace=None, hspace=None):self.validate = Truefor key in ["left", "bottom", "right", "top", "wspace", "hspace"]:setattr(self, key, mpl.rcParams[f"figure.subplot.{key}"])self.update(left, bottom, right, top, wspace, hspace)def update(self, left=None, bottom=None, right=None, top=None,wspace=None, hspace=None):"""Update the dimensions of the passed parameters. *None* means unchanged."""if self.validate:if ((left if left is not None else self.left)>= (right if right is not None else self.right)):raise ValueError('left cannot be >= right')if ((bottom if bottom is not None else self.bottom)>= (top if top is not None else self.top)):raise ValueError('bottom cannot be >= top')if left is not None:self.left = leftif right is not None:self.right = rightif bottom is not None:self.bottom = bottomif top is not None:self.top = topif wspace is not None:self.wspace = wspaceif hspace is not None:self.hspace = hspace

案例:subplots_adjust()修改间距验证

import matplotlib.pyplot as plt# 原始间距配置
fig,ax=plt.subplots(3,3)
print(vars(fig.subplotpars))
# 通过subplots_adjust()设置间距配置
plt.subplots_adjust(left=0.1,bottom=0.1,right=0.9,top=0.9,wspace=0.1,hspace=0.1)
print(vars(fig.subplotpars))
plt.show()

输出:

{'validate': True, 'left': 0.125, 'bottom': 0.125, 'right': 0.9, 'top': 0.88, 'wspace': 0.2, 'hspace': 0.2}
{'validate': True, 'left': 0.1, 'bottom': 0.1, 'right': 0.9, 'top': 0.9, 'wspace': 0.1, 'hspace': 0.1}

原始间距设置

subplots_adjust()修改间距后

tight_layout函数概述

tight_layout函数的功能为子图的内边距。备注:对axes()函数生成的子图无效。

函数的签名为matplotlib.pyplot.tight_layout(*, pad=1.08, h_pad=None, w_pad=None, rect=None)

函数的参数如下:

  • pad:所有子图整体边缘相对于图像边缘的内边距,距离单位为字体大小的比例(小数,与rcParams["font.size"]相关)。可选参数。浮点数。默认值为1.08
  • h_pad, w_pad:子图之间的内边距,距离单位为字体大小的比例(小数)。可选参数。浮点数。默认值为pad
  • rect:绘制子图的矩形区域的归一化坐标。可选参数。4元组(left, bottom, right, top)。默认值为(0, 0, 1, 1)

tight_layout函数原理

根据以下源码可知pyplot.tight_layout()函数主要通过matplotlib.tight_layout模块相关函数构造子图间距设置,最终通过figure.Figure.subplots_adjust函数更新设置。

pyplot.tight_layout()源码

def tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None):gcf().tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)

figure.Figure.tight_layout()源码

def tight_layout(self, *, pad=1.08, h_pad=None, w_pad=None, rect=None):from .tight_layout import (get_renderer, get_subplotspec_list, get_tight_layout_figure)from contextlib import suppresssubplotspec_list = get_subplotspec_list(self.axes)if None in subplotspec_list:_api.warn_external("This figure includes Axes that are not ""compatible with tight_layout, so results ""might be incorrect.")renderer = get_renderer(self)ctx = (renderer._draw_disabled()if hasattr(renderer, '_draw_disabled')else suppress())with ctx:kwargs = get_tight_layout_figure(self, self.axes, subplotspec_list, renderer,pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)if kwargs:self.subplots_adjust(**kwargs)

案例:应用tight_layout后验证间距配置

import matplotlib.pyplot as plt# 原始间距配置
fig,ax=plt.subplots(3,3)
print(vars(fig.subplotpars))
# 设置tight_layout之后的默认间距配置
plt.tight_layout()
print(vars(fig.subplotpars))
# 设置tight_layout内边距之后的间距配置
plt.tight_layout(h_pad=2.5,w_pad=2.5)
print(vars(fig.subplotpars))
plt.show()

输出为:

{'validate': True, 'left': 0.125, 'bottom': 0.125, 'right': 0.9, 'top': 0.88, 'wspace': 0.2, 'hspace': 0.2}
{'validate': True, 'left': 0.0779513888888889, 'bottom': 0.09652777777777778, 'right': 0.9566261574074074, 'top': 0.9486111111111112, 'wspace': 0.42123244337593335, 'hspace': 0.5247524752475248}
{'validate': True, 'left': 0.0779513888888889, 'bottom': 0.0965277777777778, 'right': 0.9566261574074075, 'top': 0.9486111111111111, 'wspace': 0.6248542240052247, 'hspace': 0.8996088657105613}

扩展

通过设置rcParams['figure.autolayout']=True可图像自动应用tight_layout

## Figure layout
#figure.autolayout: False  # When True, automatically adjust subplot# parameters to make the plot fit the figure# using `tight_layout`
#figure.constrained_layout.use: False  # When True, automatically make plot# elements fit on the figure. (Not# compatible with `autolayout`, above).
#figure.constrained_layout.h_pad:  0.04167  # Padding around axes objects. Float representing
#figure.constrained_layout.w_pad:  0.04167  # inches. Default is 3/72 inches (3 points)
#figure.constrained_layout.hspace: 0.02     # Space between subplot groups. Float representing
#figure.constrained_layout.wspace: 0.02     # a fraction of the subplot widths being separated.

matplotlib之pyplot模块——调整子图布局(subplots_adjust、tight_layout)相关推荐

  1. matplotlib之pyplot模块——清除子图、清除图形、删除子图、设置当前子图(cla()、clf()、delaxes()、sca())

    当前有效matplotlib版本为:3.4.1. cla函数 cla函数的作用是清空当前子图(相当于将当前子图格式化为默认空子图,子图本身并没有被删除). 函数的定义签名为matplotlib.pyp ...

  2. matplotlib之pyplot模块——饼图(pie():圆环图(donut)、二层圆环图、三层圆环图(旭日图))

    在matplotlib中pie()不单可以绘制饼图,还可以绘制圆环图(donut).圆环图可以看成饼图的变种,matplotlib没有提供专门绘制圆环图的接口. 在matplotlib之pyplot模 ...

  3. matplotlib之pyplot模块plot函数基础二(线条外观:格式字符串fmt)

    matplotlib之pyplot模块plot函数基础一(函数功能.xy参数基本取值,多组数据)简单说明了plot函数绘制线条的基本功能. plot函数的基本调用签名为plot([x], y, [fm ...

  4. pyplot绘制图片_使用matplotlib的pyplot模块绘图的实现示例

    1. 绘制简单图形 使用 matplotlib 的pyplot模块绘制图形.看一个 绘制sin函数曲线的例子. import matplotlib.pyplot as plt import numpy ...

  5. matplotlib之pyplot模块——获取/设置对象属性值(setp()、getp/get())

    当前有效matplotlib版本为:3.4.1. 概述 pyplot模块提供了获取/设置对象属性值的接口.功能类似于Python内置函数getattr和setattr.从源码上来看,get()是get ...

  6. matplotlib之pyplot模块坐标轴标签设置(xlabel()、ylabel())

    在pyplot模块中可以使用xlabel()和ylabel()函数设置x轴y轴的标签.这两个函数的使用方法非常相似. 使用xlabel()设置x轴标签 函数签名为matplotlib.pyplot.x ...

  7. matplotlib之pyplot模块——获取或设置坐标轴刻度及标签(xticks、yticks)

    概述 xticks和yticks函数的作用都是获取或设置坐标轴的刻度及标签.其中 xticks函数作用是获取或设置x坐标轴的刻度及标签. yticks函数作用是获取或设置y坐标轴的刻度及标签. 两者参 ...

  8. matplotlib之pyplot模块之饼图(pie():基础参数,返回值)

    pie()函数概述 pie()函数用于绘制饼图. pie()的函数签名为matplotlib.pyplot.pie(x, explode=None, labels=None, colors=None, ...

  9. matplotlib之pyplot模块——填充多边形(fill)

    概述 fill函数的功能是根据结点之间连线的封闭区域绘制多边形. fill函数的签名为:matplotlib.pyplot.fill(*args, data=None, **kwargs) 参数说明如 ...

最新文章

  1. linux下如何判断oracle数据库tns是否设置正常
  2. 【数字信号处理】线性时不变系统 LTI ( 判断某个系统是否是 “ 非时变 “ 系统 | 案例二 )
  3. Bootstrap(8) 路径分页标签和徽章组件
  4. 小白2分钟学会Visual Studio将引用包打包到NuGet上
  5. Web前端工程师,互联网行业,炙手可热的翘楚!
  6. [UIKit学习]03.关于UILable
  7. Java基础篇:短路逻辑运算符
  8. FreeSWITCH 初步
  9. 不属于python第三方程序_安装 selenium 对于python而言属于一个第三方的模块
  10. ps零基础学习计算机,如何零基础学习PS?写给新手朋友的一些经验
  11. Delphi7 动态数组
  12. Python植物大战僵尸源代码及素材
  13. API多帐户跨平台MT4跟单系统如何选择服务器?
  14. codebook码本算法
  15. Deecamp2019年试题A卷详解和感受
  16. ecilpse写html图片,eclipse怎么导入图片
  17. 手机html5翻页效果代码,jquery html5手机端翻书效果_手指滑动书本翻页效果代码
  18. 前端入门 02:HTML入门
  19. 区块链能否助力版权“突围”?
  20. C51单片机实现串口通信

热门文章

  1. 南京软博会圆满落幕,数睿数据企业级无代码受关注
  2. 加速!加速!西数万转硬盘猛禽RAID测试
  3. Centos安装QQ
  4. 百度霸屏精准引流是怎么做的? 百度霸屏引流方法
  5. mysql初始化root密码_MySQL初始化root密码的正确操作流程
  6. scala函数式编程系列(七)--- 模式匹配和偏函数
  7. java错误代码1638_Android studio报: java.lang.ExceptionInInitializerError 错误
  8. CTS2018+1没去记APIO2018+1游记
  9. 【基础操作】ubuntu解压zip文件乱码
  10. 小项目——涂鸦图片数据挖掘