Matplotlib学习笔记——创建多子图

创建多子图

有时候需要从多个角度对数据进行对比。Matplotlib为此提出了子图的概念:在较大的图形中同时放置一组较小的坐标轴。这些子图可能是画中画、网格图,或者是其他更复杂的布局形式。

plt.axes:手动创建子图

创建坐标轴的最基本的方法就是使用plt.axes 函数。这个函数的默认配置是创建一个标准的坐标轴,填满整张图。它还有一个可选参数,由图形坐标系统的四个值构成。这四个值分别表示坐标系统的[bottom, left, width, height],数值的取值范围是左下角(原点)为0,右上角为1.

#创建一个画中画
import matplotlib.pyplot as plt
%matplotlib inline
ax1 = plt.axes()
ax2 = plt.axes([0.65, 0.65, 0.2, 0.2])

这里写图片描述

#面向对象的画图接口中类似的命令由fig.add_axes(),下面用这个命令创建两个竖直排列的坐标轴
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4],xticklabels=[], ylim=(-1.2, 1.2))
ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4], ylim=(-1.2, 1.2))
x = np.linspace(0, 10)
ax1.plot(np.sin(x))
ax2.plot(np.cos(x))

这里写图片描述

plt.subplots:用一行代码创建网格

fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')
for i in range(2):
    for j in range(3):
        ax[i, j].text(0.5, 0.5, str((i, j)),fontsize=18, ha='center')
fig

这里写图片描述

plt.GridSpec:实现更复杂的排列方式

如果想实现不规则的多行多子列子图网格,plt.GridSpec()是更好的工具。plt.GridSpec()对象本身不能直接创建一个图形,他只是plt.subplot()命令可以识别的一个简易接口。

#创建一个带行列间距的2x3的网格
grid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3)
plt.subplot(grid[0, 0])
plt.subplot(grid[0, 1:])
plt.subplot(grid[1, :2])
plt.subplot(grid[1, 2]);

这里写图片描述

#应用plt.GridSpec创建多轴频次直方图
#创建一些正太分布数据
mean = [0, 0]
cov = [[1, 1], [1, 2]]
x, y = np.random.multivariate_normal(mean, cov, 3000).T

#设置坐标轴和网格配置方式
fig = plt.figure(figsize=(6,6))
grid = plt.GridSpec(4,4, hspace=0.2, wspace=0.2)
main_ax = fig.add_subplot(grid[:-1, 1:])
y_hist = fig.add_subplot(grid[:-1, 0], xticklabels=[], sharey = main_ax)
x_hist = fig.add_subplot(grid[-1, 1:], yticklabels=[], sharex = main_ax)

#主坐标轴画散点图
main_ax.plot(x, y, 'ok', markersize=3, alpha=0.2)

#次坐标轴画频次直方图
x_hist.hist(x, 40, histtype='stepfilled', orientation='vertical', color='gray')
x_hist.invert_yaxis()
y_hist.hist(y, 40, histtype='stepfilled', orientation='horizontal', color='gray')
y_hist.invert_xaxis()

这里写图片描述

猜你喜欢

转载自blog.csdn.net/jasonzhoujx/article/details/81774476