matplotlib教程学习笔记

如何使用tight_layout?

tight_layout作用于ticklabels, axis, labels, titles等Artist

简单的例子

import matplotlib.pyplot as plt
import numpy as np

下面的例子和constrained_layout中的是一样的,notebook没有显示出其中的问题,就是labels被遮挡了

plt.rcParams['savefig.facecolor'] = "0.8"
def example_plot(ax, fontsize=12):
ax.plot([1, 2]) ax.locator_params(nbins=3)
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title', fontsize=fontsize) plt.close('all')
fig, ax = plt.subplots()
example_plot(ax, fontsize=24)

fig, ax = plt.subplots()
example_plot(ax, fontsize=24)
plt.tight_layout()

注意到,每次作图,我们都需要通过使用plt.tight_layout()函数来激活,我们也可以通过

fig.set_tight_layout(True)使得每次作图都会自动tight布局,当然,还可以通过将

figure.autolayout rcParam设置为True来实现。

有多个plots的时候,会出现重叠的现象,通过tight_layout可以解决

plt.close('all')

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
plt.tight_layout()



tight_layout可以通过参数pad, w_pad, h_pad来设置一些布局的细节

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=2)

即使subplots的大小不一致,tight_layout依旧能够工作

plt.close('all')
fig = plt.figure() ax1 = plt.subplot(221)
ax2 = plt.subplot(223)
ax3 = plt.subplot(122) example_plot(ax1)
example_plot(ax2)
example_plot(ax3) plt.tight_layout()

对subplot2grid也有效,注意subplot2grid参数为:

shape: e.g. (3, 3) 表示\(3 \times 3\)个格子

loc: e.g. (0, 1) 表示从第一行第二列个格子开始

rowspan: 跨行

colspan: 跨列

plt.close('all')
fig = plt.figure() ax1 = plt.subplot2grid((3, 3), (0, 0))
ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2) example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4) plt.tight_layout()

arr = np.arange(100).reshape((10, 10))

plt.close('all')
fig = plt.figure(figsize=(5, 4)) ax = plt.subplot(111)
im = ax.imshow(arr, interpolation="none") plt.tight_layout()

Use with GridSpec

Gridspec 拥有自己的tight_layout()方法, 当然,plt.tight_layout也是有效的

import matplotlib.gridspec as gridspec

plt.close('all')
fig = plt.figure() gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1]) example_plot(ax1)
example_plot(ax2) gs1.tight_layout(fig)

gs.tight_layout提供rect参数,表示一个外界的框框

默认是(0, 0, 1, 1)

(x1, y1, x2, y2)

(x1, y1)矩形限制框左下角点

(x2, y2)矩形限制框右上角点

fig = plt.figure()

gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1]) example_plot(ax1)
example_plot(ax2) gs1.tight_layout(fig, rect=[0, 0, 0.5, 1])

这个功能可以很好的用在分割图形,以及分块操作上

fig = plt.figure()

gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1]) example_plot(ax1)
example_plot(ax2) gs1.tight_layout(fig, rect=[0, 0, 0.5, 1]) gs2 = gridspec.GridSpec(3, 1) for ss in gs2:
ax = fig.add_subplot(ss)
example_plot(ax)
ax.set_title("")
ax.set_xlabel("") ax.set_xlabel("x-label", fontsize=12) gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.5) # We may try to match the top and bottom of two grids ::
#为了让俩块图形上下一致,需要进行下面的操作
top = min(gs1.top, gs2.top)
bottom = max(gs1.bottom, gs2.bottom) gs1.update(top=top, bottom=bottom)
gs2.update(top=top, bottom=bottom)
plt.show()

但是呢,Title和右边的边边不齐,所以框框是不包含title的?

fig = plt.gcf()

gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1]) example_plot(ax1)
example_plot(ax2) gs1.tight_layout(fig, rect=[0, 0, 0.5, 1]) gs2 = gridspec.GridSpec(3, 1) for ss in gs2:
ax = fig.add_subplot(ss)
example_plot(ax)
ax.set_title("")
ax.set_xlabel("") ax.set_xlabel("x-label", fontsize=12) gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.5) top = min(gs1.top, gs2.top)
bottom = max(gs1.bottom, gs2.bottom) gs1.update(top=top, bottom=bottom)
gs2.update(top=top, bottom=bottom) top = min(gs1.top, gs2.top)
bottom = max(gs1.bottom, gs2.bottom) gs1.tight_layout(fig, rect=[None, 0 + (bottom-gs1.bottom),
0.5, 1 - (gs1.top-top)])
gs2.tight_layout(fig, rect=[0.5, 0 + (bottom-gs2.bottom),
None, 1 - (gs2.top-top)],
h_pad=0.5)

Legend and Annotations

fig, ax = plt.subplots(figsize=(4, 3))
lines = ax.plot(range(10), label='A simple plot')
ax.legend(bbox_to_anchor=(0.7, 0.5), loc='center left',)
fig.tight_layout()
plt.show()

有些时候,我们不希望legend也在tight_layout的掌控范围之内,这个时候,我们可以设置leg.set_in_layout(False)

fig, ax = plt.subplots(figsize=(4, 3))
lines = ax.plot(range(10), label='B simple plot')
leg = ax.legend(bbox_to_anchor=(0.7, 0.5), loc='center left',)
leg.set_in_layout(False)
fig.tight_layout()
plt.show()

Use with AxesGrid1

没看懂

from mpl_toolkits.axes_grid1 import Grid

plt.close('all')
fig = plt.figure()
grid = Grid(fig, rect=111, nrows_ncols=(2, 2),
axes_pad=0.25, label_mode='L',
) for ax in grid:
example_plot(ax)
ax.title.set_visible(False) plt.tight_layout()

Colorbar

plt.close('all')
arr = np.arange(100).reshape((10, 10))
fig = plt.figure(figsize=(4, 4))
im = plt.imshow(arr, interpolation="none") plt.colorbar(im, use_gridspec=True) plt.close('all')
arr = np.arange(100).reshape((10, 10))
fig = plt.figure(figsize=(4, 4))
im = plt.imshow(arr, interpolation="none") plt.colorbar(im, use_gridspec=True) plt.tight_layout()

from mpl_toolkits.axes_grid1 import make_axes_locatable

plt.close('all')
arr = np.arange(100).reshape((10, 10))
fig = plt.figure(figsize=(4, 4))
im = plt.imshow(arr, interpolation="none") divider = make_axes_locatable(plt.gca())
cax = divider.append_axes("right", "5%", pad="3%")
plt.colorbar(im, cax=cax) plt.tight_layout()

函数链接

plt.tight_layout

matplotlib 进阶之Tight Layout guide的更多相关文章

  1. matplotlib 进阶之Constrained Layout Guide

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

  2. Safe Area Layout Guide

    原文:Safe Area Layout Guide Apple在iOS 7中引入了topLayoutGuide和bottomLayoutGuide作为UIViewController属性.它们允许您创 ...

  3. xcode9报错 Safe Area Layout Guide before iOS9.0

    运行工程的时候会遇到  Safe Area Layout Guide before iOS9.0 这是因为xcode9  storyboard的设置里面多了 个 Safe Area Layout Gu ...

  4. Xcode 9.0 报错, Safe Area Layout Guide Before IOS 9.0

    Xcode 9.0 新建工程报错 xcode Safe Area Layout Guide Before IOS 9.0 如下图,在Builds for 选择iOS9.0 and Later,不勾选U ...

  5. Safe Area Layout Guide before iOS 9.0

    今天使用Xcode9.1重建项目,什么都没写运行报错:Safe Area Layout Guide before iOS 9.0!目前为止,不晓得原因,现记录解决方法:

  6. matplotlib 进阶之Legend guide

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

  7. Log4j2进阶使用(Pattern Layout详细设置)

    1.进阶说明 通过配置Layout打印格式化的日志, Log4j2支持很多的Layouts: CSV GELF HTML JSON Pattern Serialized Syslog XML YAML ...

  8. iOS---------- Safe Area Layout Guide before iOS 9.0

    如果你们的项目不做iOS9以下支持就打开main.storyboard    去除Use safe Area Layout 如果不考虑iOS9以下支持就按照下面的步骤 选中控制器,右边面板的Build ...

  9. 【python】matplotlib进阶

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

随机推荐

  1. react动态添加样式:style和className

    react开发过程中,经常会需要动态向元素内添加样式style或className,那么应该如何动态添加呢??? 一.react向元素内,动态添加style 例如:有一个DIV元素, 需要动态添加一个 ...

  2. Linux之sftp服务

    Linux之sftp服务 一.sftp介绍转自:[1]Linux如何开启SFTP https://www.cnblogs.com/xuliangxing/p/7120205.htmlSFTP是Secu ...

  3. fastJson序列化

    在pojo实体中有map<String,Object>的属性,有个key是user它存储在数据库中是用户的id数组,而在aop里会对这个属性做用户详细信息查询并重新put给user.在做J ...

  4. RTTI (Run-time type information) in C++

    In C++, RTTI (Run-time type information) is available only for the classes which have at least one v ...

  5. Reactor之发射器(Flux、Mono)转换操作函数

    数据合并函数 由于业务需求有的时候需要将多个数据源进行合并,Reactor提供了concat方法和merge方法: concat public static <T> Flux<T&g ...

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

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

  7. 象群游牧算法-Matlab

    1. 适应度函数: function z=chaffer(x)%chaffer函数x=(0...0) f(x)=0 x[-10,10]%%没测 n=10; s1=0; for i=1:n s1=s1+ ...

  8. C# SAP Connector .NET Framework 4.5 版本下载

    公司对接 SAP 数据使用 SAP Connector 程序,主要是两个类库:sapnco.dll.sapnco_utils.dll 但是没想到它的版本如此混乱,.NET 2.0 和 .NET 4.0 ...

  9. java面向对象类的继承~ 匿名类 ;多态特性;强制类型转换

    类的继承 创建子类语法:     修饰符 class 子类名 extends 父类名{        } 匿名子类语法: 直接实例化,过程中通过匿名类 继承父类,在实例化过程中将子类匿名 <父类 ...

  10. WSL docker打通容器间通信和追加端口映射

    最近在docker中搭建一个服务,需要有多个容器通信.这里简单记录一下如何在容器间进行通信,同时说一下已经存在的容器如何追加端口映射. 增加网桥 容器间通信的目的是不适用IP而是使用容器名称进行网络通 ...