Iterate over ax.spines.items and related functions

Screen Link: Hi, I’m working on automation of ax.tick_params function based on this loop

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

Given in dataquest mission

My ideal is:

fig_1= plt.figure(figsize =(5,10))
for sp in range(0,2):
    ax= fig_1.add_subplot(2,1,sp+1)
    for axis in ax.tick_params():

What I expected to happen: I expect it to remove all the ticks on chart. However, I got an error:
'NoneType' object is not iterable

I tried reading the documents but couldnt really understand it.
A couple of questions:

  1. I dont understand the structure of:
for key,spine in ax.spines.items():

The normal syntax for the code is: ax.spines["right"].set_visible(False) . Can someone explain to me how the loops work please?

  1. I tried to read the document to figure which part is iterable but couldnt do it. Could anyone give me resources to learn how to read the document?

Thank you

1 Like

Hey there!

ax.spines is a dictionary — using the dict.items() method returns a view object containing tuples of the key and spine values of the dictionary.

When you loop over this view object, you access each key, value pairing in the dictionary, then index the key to get access to the spine properties — each key in the dictionary points to it’s respective spine position (e.g. right, left, top, bottom).

ax.tick_params is not a dictionary — it’s a method you can pass arguments into in order to turn certain parameters on/off. More on that here:


I have a problem with the imagination of this dictionary you mentioned.

What I know:

There are two ways to write this code:

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

I assume that the second version does things from the first version(same way). If so then, [‘right’], ['left] etc, these are values from ax.spines dictionary? Does it mean that four directions: top, bottom, left and right - are the only key-value pairs from this dictionary? Does it mean, also, that the key is the same for each of them? If I understand it correctly spines is the key/keys. But, If it’s this way, how’s possible that the dictionary has the same key name for each value: top, bottom, left and right?

And lastly, why there is no mention in the documentation about the “dictionary’s property” of ax.spines? :confused:

This approach:

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

…is great. I am totally in favour of this idea: it’s simple, short and zen. Just don’t understand what’s behind the curtain.