'numpy.ndarray' object has no attribute 'plot' - cannot graph subplots

846 Views Asked by At

Question:

Perform following actions:

Create a subplots figure with 3 rows and 4 columns and a figsize of 15 by 15 Plot the lines = , =2 , =3 , =4 ,... =10 , =11 , =12 in the respective subplots. So, = in the 0th row, 0th column, =2 in the 0th row, 1th column, etc. Use the variable x that we have already created for you as , then calculate your own . Call this y_new (within a for loop).

Here is my code. I don't know why it keeps showing 'numpy.ndarray' object has no attribute 'plot'.

x = np.arange(0,100)

fig, axes = plt.subplots(nrows=3, ncols=4, figsize=(15,15))
fig.suptitle('Graphs of Various Functions')
fig.tight_layout()


for n in range(12):
    y = x*(n+1)
    if n < 4:
        row = [0]
        col = [n]
        ax = axes[row][col]
        ax.plot(x,y)
        ax.set_title('{}*x'.format(y))
    elif n <8:
        row = [1]
        col = [n-4]
        ax = axes[row][col]
        ax.plot(x,y)
        axes.set_title('{}*x'.format(y));
    elif n < 13:
        row = [2]
        col = [n-8]
        ax = axes[row][col]
        ax.plot(x,y)
        axes.set_title('{}*x'.format(y));
1

There are 1 best solutions below

0
On

I figured out where I messed up - by putting the variables for row and col inside brackets, I was creating a two dimensional array instead of just assigning an integer value to the variable name.

with the loop as I wrote it, when I tried to plot it, row would have been:

Row:

array([],
      [0])

The correct code would be:

x = np.arange(0,100)

fig, axes = plt.subplots(nrows=3, ncols=4, figsize=(15,15))
fig.suptitle('Graphs of Various Functions')
fig.tight_layout()


for n in range(12):
    if n < 4:
        row = 0
        col = n
    elif n < 8:
        row = 1
        col = n-4
    elif n < 13:
        row = 2
        col = n-8
    
    y_new = x*(n+1)
    ax = axes[row][col]
    ax.plot(x,y_new)
    ax.set_title('{}*x'.format(n+1))