如何在for循环中按顺序定位matplotlib子图ax完成批量绘图
正确实现方案
行优先遍历二维子图数组的核心逻辑是:用循环序号i对子图总列数取整得到行索引,取余得到列索引,修改后代码如下:
import numpy as np import matplotlib.pyplot as plt from scipy.stats import gaussian_kde from numpy.polynomial.polynomial import polyfit # 先明确子图列数 cols = measurements // 3 fig, ax = plt.subplots(nrows=3, ncols=cols, facecolor='w', sharex=True) for i in range(measurements): try: x = self.len.iloc[:,i] y = self.dfr.iloc[:,i] inds = ~np.logical_or(np.isnan(x), np.isnan(y)) x = x[inds] y = y[inds] xy = np.vstack([x,y]) z = gaussian_kde(xy)(xy) b, m = polyfit(x, y, 1) # 行优先索引:行号=i//总列数,列号=i%总列数 current_ax = ax[i//cols, i%cols] current_ax.scatter(x, y, c=z, s=50, cmap='jet', edgecolor='none', label=None, picker=True, zorder=2) current_ax.plot(x, b + m * x, '-') current_ax.set_xlim(0,100) except KeyError: pass # 可选优化:如果measurements不是3的整数倍,隐藏多余的空白子图 for j in range(i+1, 3*cols): ax[j//cols, j%cols].set_visible(False) plt.show()
关键说明
- 之前的写法错误原因是硬编码了行计算的除数为3,和实际子图列数
measurements//3不匹配,导致索引越界或者顺序错误 - 索引
ax[i//cols, i%cols]完全符合行优先的遍历要求:先遍历第0行所有列,再遍历第1行所有列,依次类推 - 原代码中
edgecolor=''在高版本matplotlib中会触发警告,修改为edgecolor='none'兼容性更好
内容的提问来源于stack exchange,提问作者Etiende
相关产品推荐
相关产品推荐

