使用 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
来分隔 data+fit 和残差之间的每个子图之前,它工作得很好,但我得到的是子图之上有一个凌乱的图(图已缩小以查看下面的子图):
我想要的是 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()
关于Python - 将残差添加到 for 循环生成的子图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44379168/