Subplot for several dataFrames

26 Views Asked by At

I have several dataframes that are in one Folder, so an iterative for loop for importing and reading each dataset from the folder is writen, however to plot each dataset using subplots in order to plot them in 2 rows, 3 columns subplot, a list of the dataframes are created, but when to call the function to subplot the dataframes this error occurs AttributeError: 'numpy.ndarray' object has no attribute 'plot', does anyone have a idea how to make this plots work?

    numRows =2
    numCols =3
    print(type(numRows), type(numCols))
    figure, ax = plt.subplots(numRows, numCols)
    i =0
    print(type(i))

    for data in dataFrameList:
        dataFrameList=pd.DataFrame(data)
        #print(type(dataFrameList))
        row = i // numCols
        col = i % numCols

        ax = ax.plot(row,col)
        ax.plot(dataFrameList[i]['a'], dataFrameList[i]['b'])
        ax.set_title("DataFrame Name = " + str(i))

        # Adjust the layout and spacing
        plt.tight_layout()

        data += 1
        # Combine all the operations and display
        plt.show()

I'm excpecting subplots of the dataframes that are saved in the dataFrameList

1

There are 1 best solutions below

0
bona_rivers On

There are quite a bit of errors in your code and you should provide the whole code, since we don't know what is in the dataFrameList and also which lines throws the error.

In any case the main issue I see is that you get data from the dataFrameList but then you use that variable to store your array. Moreover when you want to call the position in the subplot you should use ax[i, j].plot(whatever you want to plot). You are also not updating the index for plot and data += 1 is not needed since that is updated by the for loop if you don't change dataFrameList. Finally the call for the dataframe in the plot was not correct and the show() and tight_layout() should be applied only at the end of the for loop.

Here is something fixed, but since we don't see the entire code is not necessarily going to work. The way I update the index for the plotting is not the best one, but since we don't know the structure of dataFrameList is difficult to do it properly.

numRows = 2
numCols = 3
figure, ax = plt.subplots(numRows, numCols)
i = 0
j = 0
flag = True

for data in dataFrameList:
    df=pd.DataFrame(data)

    ax[i, j].plot(df['a'], df['b'])
    ax[i, j].set_title("DataFrame Name = " + str(data))
    
    if flag:
       i += 1
       flag = False
    else:
       j += 1
       i = 0
       flag = True

# Adjust the layout and spacing
plt.tight_layout()

# Combine all the operations and display
plt.show()