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
There are two issues here:
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With