Clarifying <for key,spine in ax.spines.items()>

Hello, everyone!

I was doing Dataquest’s mission and I struggled in one instruction:

  • “Hide all of the spines.”

Finally, after viewing the answer and digging into Google, StackOverflow, and DQ’s community, I understood what was happening to accomplish the mission, so I want to share it with you.

Before, some context.

That instruction belongs to Step 2, Improving Plot Aesthetics.
It has to do with matplotlib’s object Spine. “Spines are the lines connecting the axis tick marks and noting the boundaries of the data area” - source

Ok, why use a for loop then?

Well, for each plot four spines are created automatically. To increase data-chunk in the plot, it is recommended erase these spines.

Spine object looks like this: <matplotlib.spines.Spine object at 0x7f06981446a0>
They are stored as a Python’s dictionary, with the key being the spine’s position and the value is the spine’s object, the same as above.

To ‘erase’ them, you have to use the following method:
With ‘Spine’ being that same long object.

A quick way to do so is, you’ve got it, a for loop!

When itinerating through a dictionary the return will be the dict’s key, not the value.
But, to use that method we need its value!
To achieve this, we can use the item() method. It returns a list of tuples, inside each of the tuples we have the key followed by the value.

So, when doing for key,spine in ax.spines.items() we are telling Python to return a list of tuples of the Axe’s Spine’s object, store the key as key, and the valuet as spine. Only then we can quickly set its visibility to False.

Here’s what is shaping behind the scene:

  • ax.spines returns a dictionary: {‘left’ : <matplotlib.spines.Spine object at 0x7f06981446a0>, …}

  • ax.spines.items() returns a list of tuples: [('left, <matplotlib.spines.Spine object at 0x7f06981446a0>), (…), (…)]

  • the for loop get each one of the tuples and store the tuple[0] as key and tuple[1] as spine;

  • the method is placed for each one of the spines, setting all of them to Visibility as False.

I hope it didn’t get too confusing… My English is not that good. Sorry.
If any doubts, please tell me!