matplotlib 进阶之Tight Layout guide

摘要:
目录UsewithGridSpecLegendandAnnotationsUsewithAxesGrid1Colorbar函数链接matplotlib的简单示例教程了解如何使用紧身_布局紧身_艺术家(如ticklabels、axis、labels和title importmatplotlib.pyplotaspltimportnumyas)的布局工作原理的一个简单示例

目录

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 imes 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》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇NumPy位操作使用Microsoft的IoC框架:Unity来对.NET应用进行解耦下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

python的2D绘图库matplotlib

matplotlib的官方文档https://matplotlib.org/api/,以下介绍基本操作。 1、指定画布 画布的像素大小为指定画布的尺寸figsize及每尺寸表达的像素点数dpi的乘积。 plt.figure(figsize=(5,5),dpi=100)#figsize指定画布的大小(单位为英寸),dpi指定每英寸点(像素点)的个数 可参看官...

Matplotlib基础--直方图,分桶和密度

接着上篇,一个简单的直方图可以是我们开始理解数据集的第一步。前面我们看到了 Matplotlib 的直方图函数,我们可以用一行代码绘制基础的直方图,当然首先需要将需要用的包导入 Pycharm: import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn-white')...

Ubuntu 18.04升级matplotlib 3.5

背景 需要使用到matplotlib 3.5的新特性决定升级搜索pip源发现python 3.6最高支持matplotlib 3.2而matplotlib 3.5仅适配python 3.7+ 安装 一定不要尝试卸载18.04自带python 3.6否则系统会崩溃 sudo apt install python3.8 依赖 安装3.8包管理工具 sudo...

数据可视化:python matplotlib小试牛刀

Matplotlib有两个模块: 1) 绘图API:pyplot, 可这样导入import matplotlib.pyplot as plt    2)集成库:pylab, 是matplotlib Scipy Numpy的集成库 import pandas as pd import matplotlib.pyplot as plt from pylab i...

Python--matplotlib

无论你工作在什么项目上,IPython都是值得推荐的。利用ipython --pylab,可以进入PyLab模式,已经导入了matplotlib库与相关软件包(例如Numpy和Scipy),额可以直接使用相关库的功能。 本文作为学习过程中对matplotlib一些常用知识点的整理,方便查找。 这样IPython配置为使用你所指定的matplotlib GU...

Matplotlib基础--简单散点图

2.简单散点图 接着上一章讲的,另一种常用的图表类型是简单散点图,它是折线图的近亲。不像折线图,图中的点连接起来组成连线,散点图中的点都是独立分布的点状、圆圈或其他形状。本节开始我们也是首先将需要用到的图表工具和函数导入到 Pycharm 中: import matplotlib.pyplot as plt plt.style.use('seaborn-w...