Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib indexing error on plotting

I have basicaly the following script. But it fails during running with the following errorTypeError: 'Figure' object does not support indexing on line axarr[0].plot(x,y). I have try to search around but found a similar error with with creating subplots... And i only adding / replacing data (I'm not sure since it is a copy of a matlab file while i don't have matlab).

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 2, 0.01)
for idx in range(1, 10):
    a = 1 + (idx - 1) / 10

    y = a ** x

    axarr, fig = plt.subplots(1,1)
    axarr[0].plot(x,y)
    axarr.axis([0, 4, 0, 85])
    axarr[0].grid(True)
    plt.show()

Probably i get this error because i use a figure in a loop but it looks that it fails on iteration 1 all ready. So what do i wrong or what could better so that this works(with almost equal to matlab file see part of script below)?
I hope somebody can help.

The matlab file equal sample is this:

x = 0:0.01:4;
for idx = 1:10 
a = 1 + (idx-1)/10;

y = a.^x;
z = 2 * y
subplot(111)
plot(x,y)
hold on
plot(x(1:400),z)
axis([0 4 0 85])
pause
hold off

end
like image 497
Jan-Bert Avatar asked Sep 01 '17 04:09

Jan-Bert


Video Answer


1 Answers

There are two issues here:

  1. The return of plt.subplots is a tuple of (Figure, array of Axes). The asssignment has hence to be

    fig, axarr = plt.subplots(1,1)
    
  2. The above does not completely solve the problem, as you would then end up with a similar error (TypeError: 'AxesSubplot' object does not support indexing). This is due to the fact that by default plt.subplots reduces the array of Axes to a single axes in case only one column and one row are used. This behaviour is controlled by the squeeze argument. Valid ways to use plt.subplots are thus

    fig, axarr = plt.subplots(1,1)
    axarr.plot(x,y)
    

    or

    fig, axarr  = plt.subplots(1,1, squeeze=False)
    axarr[0,0].plot(x,y)
    

    Note that you wouldn't need need 1,1 as argument, as those are the defaults.

like image 114
ImportanceOfBeingErnest Avatar answered Sep 24 '22 01:09

ImportanceOfBeingErnest