Improving Plot Aesthetics: Slide 8

Hello everyone,
I have a question about Improving Plot Aesthetics: Slide 8.
First, why was the full code provided then the instructions on how to do it? I wanted to at least before being given the answer first.

Nonetheless, my question is about the axes.tick_params()
Why can’t I include it in the for loop of my Spine removal?
I.e. why can’t I do:

for key, spine in ax.spines.items():
        key = str(key)
        spine.set_visible(False)
        ax.tick_params(key = 'off')

The full code is:

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')
    # Add your code here.
    ax.set_xlim(1968, 2011)
    ax.set_ylim(0, 100)
    ax.set_title('' + major_cats[sp])
    ax.tick_params(bottom="off", top="off", left="off", right="off")
    for key, spine in ax.spines.items():
        key = str(key)
        spine.set_visible(False)
    
plt.legend(loc='upper right')
plt.show()

Thank you.

Screen link (for anyone reading this in the future): https://app.dataquest.io/m/147/improving-plot-aesthetics/8/comparing-gender-gap-across-degree-categories

If you try to run your code, you get the following error:

ValueError: keyword key is not recognized; valid keywords are [<removed for brevity>]

This is telling you that the key is not a valid argument for the ax.tick_params() method. When you use something in the form method(argument_name='foo'), the argument_name doesn’t get substituted.

From what I can work out, there’s not a way to include this functionality within this inner loop - it would need to sit in the outer loop (unless you put the line ax.tick_params(bottom="off", top="off", left="off", right="off") in the inner loop, in which case this line would be run 16 times instead of 4, but with the same net result.

I hope this helps to explain why you got that error. Please let me know if this answered your question.

1 Like