簡體   English   中英

matplotlib中子圖命令中的索引錯誤

[英]Index error within a subplot command in matplotlib

我不確定這是否是源代碼中的一個小錯誤,但是子圖不會分散繪制兩個形狀為(1018,)的數組。 這兩個數組都是OLS回歸的結果。 在使用指定的子圖命令之前,用變量執行散點圖從來沒有問題。 這是我的代碼如下:

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12,5))

axes[0,0].scatter(Blodgett_wue_obs,Blodgett_wue_results.fittedvalues,color ='blue')
axes[0,0].plot(Blodgett_wue_obs,Blodgett_wue_obs,'r')


File "<ipython-input-311-527571e09d59>", line 1, in <module>
runfile('/Users/JasonDucker/Documents/forJason/Paper_Plots.py', wdir='/Users/JasonDucker/Documents/forJason')

File "/Users/JasonDucker/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 685, in runfile
execfile(filename, namespace)

File "/Users/JasonDucker/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 78, in execfile
builtins.execfile(filename, *where)

File "/Users/JasonDucker/Documents/forJason/Paper_Plots.py", line 362, in <module>
axes[0,0].scatter(Blodgett_wue_obs,Blodgett_wue_results.fittedvalues,color ='blue')

IndexError: too many indices for array

任何對此問題的想法將不勝感激!

如果指定一行三列,則axes形狀為(3,) ,而不是(1,3) ,因此您將數字索引為[0][1][2]

In [8]: fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12,5))
In [9]: axes.shape
Out[9]: (3,)

使plt.subplots始終返回二維數組的最好方法是設置squeeze=False

In [8]: fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12,5), squeeze=False)
In [9]: axes.shape
Out[9]: (1,3)

或者(如果您已經將axes作為一維數組),則可以使用:

axes = np.atleast_2d(axes)

例如,

In [8]: fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12,5))
In [9]: axes.shape
Out[9]: (3,)
In[10]: axes = np.atleast_2d(axes)
In [11]: axes.shape
Out[11]: (1, 3)

In [12]: axes[0,0]
Out[12]: <matplotlib.axes._subplots.AxesSubplot at 0x1149499d0>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM