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

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():
        tick.params("off")

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

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: https://stackoverflow.com/questions/12998430/remove-xticks-in-a-matplotlib-plot

3 Likes

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

What I know:

There are two ways to write this code:
1.

...
    ax.spines["right"].set_visible(False)    
    ax.spines["left"].set_visible(False)
    ax.spines["top"].set_visible(False)    
    ax.spines["bottom"].set_visible(False)
    for key,spine in ax.spines.items():
        spine.set_visible(False)

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

…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.