Matplotlib报错:AxesSubplot对象无__getitem__属性,堆叠子图绘图求助
__getitem__属性报错 Hey there! Let's break down why you're hitting that Matplotlib error: no attribute '__getitem__' for AxesSubplot message when trying to plot stacked subplots.
核心原因
This error crops up when you try to use indexing (like axs[i][j]) on a single AxesSubplot object, instead of an array of axes. Here's the root of it:
- When you create subplots with
plt.subplots(), Matplotlib automatically "squeezes" the returned axes object to cut out unnecessary dimensions.- If you make a single subplot (
plt.subplots(1,1)), you get a standaloneAxesSubplot(not an array). - If you make a single row or column (e.g.,
plt.subplots(3,1)orplt.subplots(1,3)), you get a 1D array of axes. - Only when you have both multiple rows and columns (e.g.,
plt.subplots(2,3)) do you get a 2D array.
- If you make a single subplot (
If your code assumes you're working with a 2D array (using axs[i][j]) but you actually have a 1D array or single axes, you'll trigger this error—because a single AxesSubplot doesn't have the __getitem__ method needed for indexing.
解决方法
Here are three straightforward fixes to align your axes structure with your plotting logic:
1. Force a 2D axes array with squeeze=False
Add the squeeze=False parameter to plt.subplots()—this tells Matplotlib to always return a 2D array, even if rows or columns are 1. You can then safely use axs[i,j] indexing everywhere:
import matplotlib.pyplot as plt # Create 2 rows, 1 column of subplots, force 2D array output fig, axs = plt.subplots(nrows=2, ncols=1, squeeze=False) # Iterate through your data and plot for i in range(2): axs[i, 0].plot(data.main()[i]) # 2D indexing works even for single-column layouts
2. Match indexing to your axes structure
If you don't want to use squeeze=False, adjust how you access axes based on your actual layout:
- For a single row (1xN): Use 1D indexing like
axs[j] - For a single column (Nx1): Use 1D indexing like
axs[i] - For a single subplot: Use the axes object directly (no indexing needed)
Example for a 3-row stacked plot:
fig, axs = plt.subplots(3, 1) # Returns a 1D array [ax1, ax2, ax3] for idx, dat in enumerate(data.main()): axs[idx].plot(dat) # 1D indexing works perfectly here
3. Iterate over flattened axes
If you want to loop through all subplots without worrying about dimensions, use the flat attribute to turn any axes structure into a 1D iterator:
fig, axs = plt.subplots(2, 2) # Works for any layout: 1x3, 3x1, etc. # Loop through each axes and corresponding data point for ax, dat in zip(axs.flat, data.main()): ax.plot(dat)
Quick Debug Tip
Double-check what axs actually is by printing its type and shape:
print(type(axs)) if hasattr(axs, 'shape'): print(axs.shape)
This will tell you if you're dealing with a single axes object, 1D array, or 2D array, so you can adjust your code accordingly.
内容的提问来源于stack exchange,提问作者Jobo

