Home > Blockchain >  too many indices for array with matplotlib subplots
too many indices for array with matplotlib subplots

Time:06-27

I'm trying to plot 2 different data sets but I don't know how to fix the subplot (if i put 2,2 it works but if i try anything else it gives me an error)

fig, axs = plt.subplots(nrows=2, ncols=1)

axs[0,1].plot(adj_close['SOL-USD'])
axs[2,1].set_title('SOL')

plt.show()

error:


----> 6 axs[0,0].plot(adj_close['SOL-USD'])
      7 axs[0,0].set_title('SOL')
      8 axs[0,1].plot(adj_close['ETH-USD'])

TypeError: 'AxesSubplot' object is not subscriptable

IndexError                                Traceback (most recent call last)
Input In [356], in <cell line: 3>()
      1 #ploting the histogram
      2 fig, axs = plt.subplots(2,1,figsize=(16,8),gridspec_kw ={'hspace': 0.2, 'wspace': 0.1})
----> 3 axs[0,0].hist(returns['SOL-USD'], bins=50, range=(-0.2, 0.2))
      4 axs[0,0].set_title('SOL')
      5 axs[1,0].hist(returns['ETH-USD'], bins=50, range=(-0.2, 0.2))

IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

what it currently looks like with subplot 2,2: what it currently looks like with subplot 2,2

CodePudding user response:

what is going on here is that matplotlib.pyplot.subplots() creates an array of one dimension for axes in fig if nrows or ncols is equal to 1. You can see this by displaying the variable in your current workspace.

>>> fig, axes = plt.subplots(nrows=2, ncols=1)

>>> axes

array([<AxesSubplot:>, <AxesSubplot:>], dtype=object)

That is why an index error appears when trying to call more than one. For more documentation, here is the site to the function matplotlib.pyplot.subplots

CodePudding user response:

See the matplotlib.pyplot.subplots documentation. There is an optional argument squeeze, default True:

squeeze : bool, default: True
If True, extra dimensions are squeezed out from the returned array of Axes:

  • if only one subplot is constructed (nrows=ncols=1), the resulting single Axes object is returned as a scalar.

  • for Nx1 or 1xM subplots, the returned object is a 1D numpy object array of Axes objects.

  • for NxM, subplots with N>1 and M>1 are returned as a 2D array.

If False, no squeezing at all is done: the returned Axes object is always a 2D array containing Axes instances, even if it ends up being 1x1.

So, with the default of squeeze=True, axes will be a different shape depending on your arguments:

  • plt.subplots(1, 1) --> single Axis object
  • plt.subplots(1, n) --> 1-dimensional vector of Axis objects
  • plt.subplots(n, 1) --> 1-dimensional vector of Axis objects
  • plt.subplots(n, m) --> 2-dimensional array of Axis objects
  • Related