Improving plot aesthetics, screen 8

Hello!
Please could anyone help to undestand the following piece of code:

for key,spine in ax.spines.items():
spine.set_visible(False)

in:

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():
spine.set_visible(False)
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”)

plt.legend(loc=‘upper right’)
plt.show()

Thank you!

This is my understanding but you probably want to wait for a Dataquest moderator for a better explanation.

It’s a more efficient way to cycle through all the spines cause without it you’d have to run
ax.spines[“right”].set_visible(False)
ax.spines[“left”].set_visible(False)
ax.spines[“bottom”].set_visible(False)
ax.spines[“top”].set_visible(False)

In this scenario, ax.spines is a dictionary.
When you use dictionary.items() it returns a key/value pair of spines.items() so you’re getting two values instead of one. One is the index, and the other being the value (right, left, bottom, top).

Not sure about the order it takes but it should cycle through each spine.
First go around it’ll set “right” value to False
ax.spines[“right”].set_visible(False)

then onto “left”
ax.spines[“left”].set_visible(False)

…until it goes through all of them.

Probably not the best way to think about it, but what helps me is we’re dealing with two values in the for loop instead of one like in earlier sections of the course.
I.E.

for x in range(10):
print(x)

4 Likes

Hi, Thank you for you reply! Looks like now I see it more clearly. Yes I can see that this is a loop iterating through something
to eventually make spines invisible, however I do not understand what ax.spines.items() means. What is that? Why is .items? For what?
What was the logic behind writing this piece of code?

No problem and I’m not sure I’m the best person to explain it.
:grinning:

items() is a method of dictionary that returns a tuple of the key/value pair.
For example.
Dict = {“name” : “John”}

when you call Dict.items() you’ll get (“name”, “John”)

https://www.tutorialspoint.com/python/dictionary_items.htm

2 Likes

Thank you very much! That was very helpful. However why is that this spines is a dictionary?