如何将多个Q-Q图合并为一个3×2的Matplotlib子图?
合并Matplotlib Q-Q图为3×2子图的问题解决方法
需求背景
原本使用Matplotlib创建了6个独立的Q-Q图,每个图都绘制了距离Q-Q线±2标准差的异常值线,现在需要将这些图合并为一个3×2布局的子图。
单个Q-Q图的实现代码(效果符合预期)
f = plt.figure(1) sm.qqplot(x1, line='r', fit=False, loc = np.mean(x1), scale = np.std(x1)) abline(slope1, intercept1 + 2*np.std(x1)) abline(slope1, intercept1 - 2*np.std(x1)) plt.title('STATS250') f.show() g = plt.figure(2) sm.qqplot(x2, line='r', fit=False, loc = np.mean(x2), scale = np.std(x2)) abline(slope2, intercept2 + 2*np.std(x2)) abline(slope2, intercept2 - 2*np.std(x2)) plt.title('DATASCI306') g.show() h = plt.figure(3) sm.qqplot(x3, line='r', fit=False, loc = np.mean(x3), scale = np.std(x3)) abline(slope3, intercept3 + 2*np.std(x3)) abline(slope3, intercept3 - 2*np.std(x3)) plt.title('MATH217') h.show()
绘制异常值线的辅助函数
def abline(slope, intercept): """Plot a line from slope and intercept""" axes = plt.gca() x_vals = np.array(axes.get_xlim()) y_vals = intercept + slope * x_vals plt.plot(x_vals, y_vals, '--') return
最初的错误尝试
尝试用subplots创建3×2子图并循环绘制时,所有异常值线都出现在最后一个子图中:
fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(9,20)) ax= axes.flatten() for i in range(6): sm.qqplot(x[i], line='r', fit=False, loc = np.mean(x[i]), scale = np.std(x[i]), ax=ax[i]) abline(slope[i], intercept[i] + 2*np.std(x[i])) abline(slope[i], intercept[i] - 2*np.std(x[i])) plt.show()
最终解决方法
修改辅助函数,传入子图的axis句柄,确保线条绘制到对应子图:
def abline2(slope, intercept, ax): """Plot a line from slope and intercept""" axes = ax x_vals = np.array(axes.get_xlim()) y_vals = intercept + slope * x_vals axes.plot(x_vals, y_vals, '--') return
调用sm.qqplot时指定ax参数,同时在调用abline2时传入对应子图的axis句柄:
sm.qqplot(x[i], line='r', fit=False, loc = np.mean(x[i]), scale = np.std(x[i]), ax=ax[i]) abline2(slope[i], intercept[i] + 2*np.std(x[i]), ax=ax[i]) abline2(slope[i], intercept[i] - 2*np.std(x[i]), ax=ax[i])
内容的提问来源于stack exchange,提问作者Hambone_McKool
相关产品推荐
相关产品推荐

