Improving Plot Aesthetics - Comparing Gender Gap Across Degree Categories - Confusion


I am going through Improving Plot Aesthetics again, and I am a little bit confused with the solution:

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')
    for key,spine in ax.spines.items():
    ax.set_xlim(1968, 2011)
    ax.tick_params(bottom="off", top="off", left="off", right="off")

# Calling pyplot.legend() here will add the legend to the last subplot that was created.
plt.legend(loc='upper right')

ax.set_title(major_cats[sp]), where does the SP come from? I get it is one of the key we called in the for loop but I just don’t really understand the logic behind it to reproduce it.

Thanks a lot!

1 Like

Hi @loicchamplong,

Good question.

What the for sp in range(0,4): loop is doing is looping through each element in the major_cats list
major_cats = ['Biology', 'Computer Science', 'Engineering', 'Math and Statistics'].

Biology = index 0
Computer Science = index 1
Engineering = index 2
Math and Statistics = index 3

In the first loop sp would = 0, in the second loop sp =1, then sp = 2, and finally sp =3. We know this because in the for loop we say sp is going to equal every number starting at 0 and going up to but not including 4 (range(0,4)).

When we set the title ax.set_title(major_cats[sp]) we are using index to access each element of our list.

The title of the first plot (sp = 0) would be `ax.set_title(major_cats[0]) which grabs element 0 from the major_cats list (i.e., ‘Biology’) and sets that first element as the title.

The title of the second plot (sp = 1) would be `ax.set_title(major_cats[1]) which grabs element 1 from the major_cats list (i.e., ‘Computer Science’) and sets that first element as the title.

and so forth.

Hope this helps,

1 Like