____tz_zs
matplotlib.pyplot.subplots
创建一个图像对象(figure) 和 一系列的子图(subplots)。
官网:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots.html (网页最下方有很多demo)
.
源码 matplotlib.pyplot.subplots
def subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True,
subplot_kw=None, gridspec_kw=None, **fig_kw):
fig = figure(**fig_kw)
axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey,
squeeze=squeeze, subplot_kw=subplot_kw,
gridspec_kw=gridspec_kw)
return fig, axs
.
参数
nrows,ncols:
- 子图的行列数。
sharex, sharey:
- 设置为 True 或者 ‘all’ 时,所有子图共享 x 轴或者 y 轴,
- 设置为 False or ‘none’ 时,所有子图的 x,y 轴均为独立,
- 设置为 ‘row’ 时,每一行的子图会共享 x 或者 y 轴,
- 设置为 ‘col’ 时,每一列的子图会共享 x 或者 y 轴。
squeeze:
- 默认为 True,是设置返回的子图对象的数组格式。
- 当为 False 时,不论返回的子图是只有一个还是只有一行,都会用二维数组格式返回他的对象。
- 当为 True 时,如果设置的子图是(nrows=ncols=1),即子图只有一个,则返回的子图对象是一个标量的形式,如果子图有(N×1)或者(1×N)个,则返回的子图对象是一个一维数组的格式,如果是(N×M)则是返回二位格式。
subplot_kw:
- 字典格式,传递给 add_subplot() ,用于创建子图。
gridspec_kw:
- 字典格式,传递给 GridSpec 的构造函数,用于创建子图所摆放的网格。
- class matplotlib.gridspec.GridSpec(nrows, ncols, figure=None, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None, width_ratios=None, height_ratios=None)
- 如,设置 gridspec_kw={'height_ratios': [3, 1]} 则子图在列上的分布比例是3比1。
**fig_kw :
- 所有其他关键字参数都传递给 figure()调用。
- 如,设置 figsize=(21, 12) ,则设置了图像大小。
返回值
fig: matplotlib.figure.Figure 对象
ax:子图对象( matplotlib.axes.Axes)或者是他的数组
示例代码
.
#!/usr/bin/python2.7
# -*- coding:utf-8 -*-
"""
@author: tz_zs
"""
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
# 创建一个子图
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
.
.
# 创建两个子图,并且共享y轴
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
.
.
# 创建4个子图,
fig, axes = plt.subplots(2, 2, subplot_kw=dict(polar=True))# polar:极地
axes[0, 0].plot(x, y)
axes[1, 1].scatter(x, y)
.
.
# 共享每列子图的x轴
plt.subplots(2, 2, sharex='col')
.
.
# 共享每行子图的y轴
plt.subplots(2, 2, sharey='row')
.
.
# 共享所有子图的x和y轴
# plt.subplots(2, 2, sharex='all', sharey='all')
plt.subplots(2, 2, sharex=True, sharey=True)
.
.
end