Improving plot aesthetics - Displaying Multiple Plots per Figure

major_cats = ['Biology', 'Computer Science', 'Engineering', 'Math and Statistics']
fig = plt.figure(figsize=(12, 12))

for sp in range(0,4):
    
    ax = fig.add_subplot(2,2,sp+1)
    ax.plot(women_degrees['Year'], women_degrees[major_cats[sp]], c='blue', label='Women')
    ax.plot(women_degrees['Year'], 100-women_degrees[major_cats[sp]], c='green', label='Men')

# Calling pyplot.legend() here will add the legend to the last subplot that was created.
plt.legend(loc='upper right')
plt.show()
major_cats = ['Biology', 'Computer Science', 'Engineering', 'Math and Statistics']
fig = plt.figure(figsize=(12, 12))

#each item in the sequence 0,1,2,3
for sp in range(0,4):
    #2X2 grid , 2 rows , 2 col, first subplot,second .. in 0-4
    ax = fig.add_subplot(2,2,sp+1)
    # plot(x, y, 'blue')  # plot x and y using blue color for women
    ax.plot(women_degrees['Year'], women_degrees[major_cats[sp]], c='blue', label='Women')

I do not understand this part:

    for sp in range(0,4):
        #2X2 grid , 2 rows , 2 col, first subplot,second .. in 0-4
        ax = fig.add_subplot(2,2,sp+1)

From the code it looks like it is adding a 2x2 grid each time in the loop which goes 4 times so that would be 8 rows and eight columns but I only get 2 columns and 4 rows:

Also I do not quite get sp in range here:

major_cats = ['Biology', 'Computer Science', 'Engineering', 'Math and Statistics']
fig = plt.figure(figsize=(12, 12))

for sp in range(0,4):

I kind of relate that there are four items in the list so it is working with that and loops 4 times but do not see any other connection in the code if this could be explained please, why is it not major_cats if it is working with list instead of sp?

@jamesberentsen Hey,

No, it is not adding 2X2 grid each time.

For simplification, this is what’s happening in for loop.
ax = fig.add_subplot(2,2,1) - 1st pass
ax = fig.add_subplot(2,2,2) - 2nd pass
ax = fig.add_subplot(2,2,3) -3rd pass
ax = fig.add_subplot(2,2,4) -4th pass

So grid is the same, we are just specifying position of the plot each time. The grid remains constant for that fig variable.
And there are only two rows and two columns.

We want to make graphs for the specified list items. So you can say that for loop is connected with the length of list.

See, you can use any variable you want. I guess they have used sp(subplot) to show subplot numbers. like subplot 1,2,3,4.

1 Like

hey @jamesberentsen

I responded to a similar post here but this has lot more details.

As @jenil2452000 has responded, the grid is not added each time. The 2X2 matrix gets created once, and only the subplots or quadrants in that one big box gets added with each loop run.

Let us know if the linked post also doesn’t help you and confuses you rather more.

1 Like

Thank you very much jenil2452000 I see how it works now

1 Like

Thanks Rucha, it was confusing for me , but I get it now.

1 Like