Python - 将残差添加到由 for 循环生成的子图中

Python - Add residuals to subplots generated by a for loop

在使用 add_axes 添加残差时,我无法让子图工作。它在没有残差的情况下运行良好,我可以将残差添加到一个图中。这是我正在做的一个例子:

首先,为了让您了解我正在绘制的内容,(t, y) 是我要绘制的数据,fit 是对数据的拟合,diff 是拟合和数据之间的差异.

t, s, fit = [], [], []
diff = []
for i in range(12):
    t.append(x / y[i])

    s.append(np.linspace(0, 1, num=100, endpoint=True))
    fit.append(UnivariateSpline(t[i], y, er, s=5e20))
    diff.append(fit[i](t[i]) - y)

这是数字:

fig = plt.figure()
for i in range(12):
    plt.subplot(4,3,i+1)
    fig.add_axes((0.,0.3,0.7,0.9))
    plt.plot(s[i], fit[i](s[i]), 'r-') # this is the fit
    plt.errorbar(t[i], y, er, fmt='.k',ms=6) # this is the data 
    plt.axis([0,1, 190, 360])

    fig.add_axes((0.,0.,0.7,0.3))       
    plot(t[i],diff[i],'or') # this are the residuals
    plt.axis([0,1, 190, 360])

所以你可以看到我生成了 12 个子图,在我添加 fig.add_axes 来分隔数据+拟合和残差之间的每个子图之前它工作得很好,但我得到的是一个混乱的图在子图之上(图已缩小以查看下面的子图):

我想要的是 12 个子图,每个子图如下所示:

通常plt.subplot(..)fig.add_axes(..)是互补的。这意味着这两个命令都会在图中创建一个轴。

但是它们的用法会有点不同。要使用 subplot 创建 12 个子图,您需要

for i in range(12):
    plt.subplot(4,3,i+1)
    plt.plot(x[i],y[i])

要使用 add_axes 创建 12 个子图,您需要执行以下操作

for i in range(12):
    ax = fig.add_axes([.1+(i%3)*0.8/3, 0.7-(i//3)*0.8/4, 0.2,.18])
    ax.plot(x[i],y[i])

其中轴的位置需要传递给 add_axes

两者都工作正常。但是组合它们并不是直接的,因为子图是根据网格定位的,而使用 add_axes 时你需要已经知道网格位置。

所以我建议从头开始。创建子图的合理且干净的方法是使用 plt.subplots().

fig, axes = plt.subplots(nrows=4, ncols=3)
for i, ax in enumerate(axes.flatten()):
    ax.plot(x[i],y[i])

每个子图可以使用轴分隔符 (make_axes_locatable) 分为 2

from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax)
ax2 = divider.append_axes("bottom", size=size, pad=pad)
ax.figure.add_axes(ax2)

因此遍历轴并对每个轴执行上述操作可以获得所需的网格。

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
plt.rcParams["font.size"] = 8

x = np.linspace(0,2*np.pi)
amp = lambda x, phase: np.sin(x-phase)
p = lambda x, m, n: m+x**(n)

fig, axes = plt.subplots(nrows=3, ncols=4, figsize=(8,6), sharey=True, sharex=True)

def createplot(ax, x, m, n, size="20%", pad=0):
    divider = make_axes_locatable(ax)
    ax2 = divider.append_axes("bottom", size=size, pad=pad)
    ax.figure.add_axes(ax2)
    ax.plot(x, amp(x, p(x,m,n)))
    ax2.plot(x, p(x,m,n), color="crimson")
    ax.set_xticks([])

for i in range(axes.shape[0]):
    for j in range(axes.shape[1]):
        phase = i*np.pi/2
        createplot(axes[i,j], x, i*np.pi/2, j/2.,size="36%")

plt.tight_layout()        
plt.show()