Matplotlib之定义布局(三)
一、在Figure中排列多个Axes
通常一次在一个Figure上需要多个Axes,通常组织成规则的网格。Matplotlib 有多种工具可用于处理坐标轴网格。可以在Figure中添加以下两种Axes:
- 使用 plt.subplots 绘制均匀状态下的子图
- 使用 GridSpec 绘制非均匀子图
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
(一)使用 plt.subplots 绘制均匀状态下的子图
返回元素分别是画布和子图构成的列表,第一个数字为行,第二个为列,不传入时默认值都为1
- figsize 参数可以指定整个画布的大小
- sharex 和 sharey 分别表示是否共享横轴和纵轴刻度
- tight_layout 函数可以调整子图的相对大小使字符不会重叠
fig, axs = plt.subplots(2, 5, figsize=(10, 4), sharex=True, sharey=True)
fig.suptitle('样例1', size=20)
for i in range(2):
for j in range(5):
axs[i][j].scatter(np.random.randn(10), np.random.randn(10))
axs[i][j].set_title('第%d行,第%d列'%(i+1,j+1))
axs[i][j].set_xlim(-5,5)
axs[i][j].set_ylim(-5,5)
if i==1: axs[i][j].set_xlabel('横坐标')
if j==0: axs[i][j].set_ylabel('纵坐标')
fig.tight_layout()
subplots是基于OO模式的写法,显式创建一个或多个axes对象,然后在对应的子图对象上进行绘图操作。
还有种方式是使用subplot这样基于pyplot模式的写法,每次在指定位置新建一个子图,并且之后的绘图操作都会指向当前子图,本质上subplot也是Figure.add_subplot的一种封装。
在调用subplot时一般需要传入三位数字,分别代表总行数,总列数,当前子图的index。
plt.figure()
# 子图1
plt.subplot(2,2,1)
plt.plot([1,2], 'r')
# 子图2
plt.subplot(2,2,2)
plt.plot([1,2], 'b')
#子图3
plt.subplot(224) # 当三位数都小于10时,可以省略中间的逗号,这行命令等价于plt.subplot(2,2,4)
plt.plot([1,2], 'g');
除了常规的直角坐标系,也可以通过projection方法创建极坐标系下的图表:
N = 150
r = 2 * np.random.rand(N)
theta = 2 * np.pi * np.random.rand(N)
area = 200 * r**2
colors = theta
plt.subplot(projection='polar')
plt.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha=0.75);
(二)使用 GridSpec 绘制非均匀子图
所谓非均匀包含两层含义
- 第一是指图的比例大小不同但没有跨行或跨列
- 第二是指图为跨列或跨行状态
利用 add_gridspec 可以指定相对宽度比例 width_ratios 和相对高度比例参数 height_ratios
fig = plt.figure(figsize=(10, 4))
spec = fig.add_gridspec(nrows=2, ncols=5, width_ratios=[1,2,3,4,5], height_ratios=[1,3])
fig.suptitle('样例2', size=20)
for i in range(2):
for j in range(5):
ax = fig.add_subplot(spec[i, j])
ax.scatter(np.random.randn(10), np.random.randn(10))
ax.set_title('第%d行,第%d列'%(i+1,j+1))
if i==1: ax.set_xlabel('横坐标')
if j==0: ax.set_ylabel('纵坐标')
fig.tight_layout()
- width_ratios 每个子图的宽度比例
- height_ratios 2行子图,设置两2个值分别表示每一行的高度比例
在上面的例子中出现了 spec[i, j] 的用法,事实上通过切片就可以实现子图的合并而达到跨图的功能。
fig = plt.figure(figsize=(10, 4))
spec = fig.add_gridspec(nrows=2, ncols=6, width_ratios=[2,2.5,3,1,1.5,2], height_ratios=[1,2])
fig.suptitle('样例3', size=20)
# sub1
ax = fig.add_subplot(spec[0, :3])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub2
ax = fig.add_subplot(spec[0, 3:5])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub3
ax = fig.add_subplot(spec[:, 5])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub4
ax = fig.add_subplot(spec[1, 0])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub5
ax = fig.add_subplot(spec[1, 1:5])
ax.scatter(np.random.randn(10), np.random.randn(10))
fig.tight_layout()
constrained约束布局tight_layout紧凑布局
(一)constrained 约束布局
constrained_layout会自动调整子图和装饰(如图例和颜色条),以便它们适合图形窗口,同时仍尽可能保留用户请求的逻辑布局。
constrained_layout 类似于 tight_layout,但使用约束求解器来确定允许它们适合的轴的大小。
在将任何轴添加到图形之前,通常需要激活 constrained_layout 。这样做的两种方法是:
-
使用subplots() 的相应参数figure()
plt.subplots(layout="constrained") -
通过rcParams激活它
plt.rcParams['figure.constrained_layout.use'] = True
在 Matplotlib 中,坐标轴(包括子图)的位置在标准化图形坐标中指定。您的轴标签或标题(有时甚至是刻度标签)可能会超出图形区域,因此会被剪掉。
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.gridspec as gridspec
import numpy as np
plt.rcParams['savefig.facecolor'] = "0.8"
plt.rcParams['figure.figsize'] = 4.5, 4.
plt.rcParams['figure.max_open_warning'] = 50
def example_plot(ax, fontsize=12, hide_labels=False):
ax.plot([1, 2])
ax.locator_params(nbins=3) # Control behavior of major tick locators.
if hide_labels:
ax.set_xticklabels([])
ax.set_yticklabels([])
else:
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title', fontsize=fontsize)
fig, ax = plt.subplots(layout=None)
example_plot(ax, fontsize=24)
为了防止这种情况,需要调整轴的位置。对于子图,这可以通过使用 调整子图参数手动完成Figure.subplots_adjust。但是,使用关键字参数指定图形layout="constrained"将自动调整
fig, ax = plt.subplots(layout="constrained")
example_plot(ax, fontsize=24)
(二)tight_layout 紧凑布局
tight_layout 自动调整子图参数,使子图适合图形区域。它可能不适用于某些情况。它只检查刻度标签、轴标签和标题的范围。
tight_layout 的替代方案是 constrained_layout
在 matplotlib 中,坐标轴(包括子图)的位置在标准化图形坐标中指定。您的轴标签或标题(有时甚至是刻度标签)可能会超出图形区域,因此会被剪掉。
import matplotlib.pyplot as plt
import numpy as np
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)
为了防止这种情况,需要调整轴的位置。对于子图,这可以通过使用 调整子图参数手动完成Figure.subplots_adjust。Figure.tight_layout自动执行此操作。
fig, ax = plt.subplots()
example_plot(ax, fontsize=24)
plt.tight_layout()
注意:matplotlib.pyplot.tight_layout()只会在调用时调整子图参数。为了在每次重新绘制图形时执行此调整,您可以调用fig.set_tight_layout(True),或者等效地,将rcParams["figure.autolayout"](默认值:False)设置为True)
三、子图上的方法
常用直线的画法为:
axhline水平axvline垂直axline任意方向
fig, ax = plt.subplots(figsize=(4,3))
ax.axhline(0.5,0.2,0.8)
ax.axvline(0.5,0.2,0.8)
ax.axline([0.3,0.3],[0.7,0.7]);
使用 grid 可以加灰色网格:
fig, ax = plt.subplots(figsize=(4,3))
ax.grid(True)
使用 set_xscale 可以设置坐标轴的规度(指对数坐标等)
fig, axs = plt.subplots(1, 2, figsize=(10, 4))
for j in range(2):
axs[j].plot(list('abcd'), [10**i for i in range(4)])
if j==0:
axs[j].set_yscale('log')
else:
pass
fig.tight_layout()


浙公网安备 33010602011771号