@@ -146,27 +146,36 @@ def __getitem__(self, key):
146146 """
147147 nrows , ncols = self .get_geometry ()
148148
149- def _normalize (key , size ): # Includes last index.
149+ def _normalize (key , size , axis ): # Includes last index.
150+ orig_key = key
150151 if isinstance (key , slice ):
151152 start , stop , _ = key .indices (size )
152153 if stop > start :
153154 return start , stop - 1
155+ raise IndexError ("GridSpec slice would result in no space "
156+ "allocated for subplot" )
154157 else :
155158 if key < 0 :
156- key += size
159+ key = key + size
157160 if 0 <= key < size :
158161 return key , key
159- raise IndexError ("invalid index" )
162+ elif axis is not None :
163+ raise IndexError (f"index { orig_key } is out of bounds for "
164+ f"axis { axis } with size { size } " )
165+ else : # flat index
166+ raise IndexError (f"index { orig_key } is out of bounds for "
167+ f"GridSpec with size { size } " )
160168
161169 if isinstance (key , tuple ):
162170 try :
163171 k1 , k2 = key
164172 except ValueError :
165173 raise ValueError ("unrecognized subplot spec" )
166174 num1 , num2 = np .ravel_multi_index (
167- [_normalize (k1 , nrows ), _normalize (k2 , ncols )], (nrows , ncols ))
175+ [_normalize (k1 , nrows , 0 ), _normalize (k2 , ncols , 1 )],
176+ (nrows , ncols ))
168177 else : # Single key
169- num1 , num2 = _normalize (key , nrows * ncols )
178+ num1 , num2 = _normalize (key , nrows * ncols , None )
170179
171180 return SubplotSpec (self , num1 , num2 )
172181
0 commit comments