Home > Net >  How to redirect looped plots to a grid
How to redirect looped plots to a grid

Time:07-11

I know that my question has been asked several times, but it took me already too much time and I can't find the solution, even if I am sure it's quite simple... The data is coming from 3 separate dataframes which are shaped the same, to get the boxplot I had to transpose the data and make some other changes...

This is my code, hope it's not too minimalistic:

columnname = list(cm)
max = len(columnname)-1
for i in range(0,max):
    cm2 = cm[columnname[i]]
    vz2 = vz[columnname[i]]
    models2 = models[columnname[i]]
    columns = [cm2, vz2, models2]
    name = str(cm2.name)
    fig, ax = plt.subplots()
    ax.boxplot(columns)
    ax.set_ylabel('$')
    ax.set_title(name)

How can I get it to a chosen grid? Just using (2,4) in subplots is not working. --> AttributeError: 'numpy.ndarray' object has no attribute 'boxplot'

CodePudding user response:

You are pretty close.... one change is you need to define the subplot() before the loop and mention the number of array (2,4) you need. Inside the loop, you need to indicate the ax[row, col]. I have updated your code and used some random numbers to generate the same below.

cm = pd.DataFrame(np.random.rand(100, 8))
vz = pd.DataFrame(np.random.rand(100, 8))
models = pd.DataFrame(np.random.rand(100, 8))

columnname = list(cm)
max = len(columnname)-1

fig, ax = plt.subplots(2,4,figsize=(15,12))

for i in range(0,max 1):
    row=i/4  #Identify the row number
    col=i%4  #Identify the column number
    cm2 = cm[columnname[i]]
    vz2 = vz[columnname[i]]
    models2 = models[columnname[i]]
    columns = [cm2, vz2, models2]
    name = str(cm2.name)
    ax[int(row), col].boxplot(columns)

Output

enter image description here

  • Related