Matplotlib自定义子图行列数问题:单行列输入报错求助
Matplotlib子图脚本行列均为1时触发TypeError问题解析
错误含义
当输入行数和列数均为1时,plt.subplots(nrows=1, ncols=1)返回的axes不是多维数组,而是单个Axes对象。你的代码尝试用axes[j]去下标访问这个对象,但单个Axes实例不支持下标操作,因此触发TypeError: 'Axes' object is not subscriptable。
解决方法
方法1:统一转换为二维数组(推荐)
用numpy的np.atleast_2d()函数,把单个Axes对象或一维数组统一转为二维数组,让后续的axes[i,j]下标访问适配所有行列组合:
修改后的完整代码:
import matplotlib.pyplot as plt import numpy as np def create_subplots(nrows, ncols): fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(8, 6)) # 统一转换为二维数组,消除维度差异 axes = np.atleast_2d(axes) x = np.linspace(0, 10, 100) for i in range(nrows): for j in range(ncols): ax = axes[i, j] y = np.sin(x + (i * ncols + j)) ax.plot(x, y) ax.set_title(f'Subplot ({i+1}, {j+1})') plt.tight_layout() plt.show() try: num_rows = int(input("Enter the number of rows for subplots: ")) num_cols = int(input("Enter the number of columns for subplots: ")) create_subplots(num_rows, num_cols) except ValueError: print("Invalid input. Please enter integers for rows and columns.")
方法2:补充行列均为1的判断分支
在原有的三元表达式中,单独添加对nrows=1且ncols=1的判断,直接返回单个Axes对象:
修改关键代码行:
ax = axes[i, j] if nrows > 1 and ncols > 1 else axes[j] if nrows == 1 and ncols > 1 else axes[i] if ncols == 1 and nrows > 1 else axes
原代码问题分析
原代码的三元表达式遗漏了nrows=1且ncols=1的边界情况,此时会错误进入axes[j]分支,但axes是单个Axes实例,无法通过下标访问,最终触发报错。
内容的提问来源于stack exchange,提问作者John Honai
相关产品推荐
相关产品推荐

