Search code examples
python-3.xmatplotlibplotaxes

Using setp to hide axes spines


I am trying to use setp in matplotlib to set the visibility of spines to False, but I get the error "AttributeError: 'str' object has no attribute 'update'". As far as I understand, with setp we can change the properties of iterable objects, and want to execute it with spines.

What is the correct syntax to effectively use setp?

Hier a MWE:

import matplotlib.pyplot as plt

x = range(0,10)
y = [i*i for i in x]

plt.plot(x,y) #Plotting x against y
axes = plt.gca() #Getting the current axis

axes.spines['top'].set_visible(False) #It works

plt.setp(axes.spines, visible=False) #It rises error

plt.show() #Showing the plot

Versions: python3.8.2, Matplotlib 3.2.1


Solution

  • axes.spines is an OrderedDict. When you iterate over a Dict or OrderedDict like this:

    for key in axes.spines:
        print(type(key))
    

    You are iterating over the keys, which are strings and have no update method. Here you can see what parameters can be set with plt.setp() by just passing in the iterable or object like so.

    plt.setp(axes.spines)
    

    This returns None, because its referring to the keys, which are strings and have no update method. Along this line of logic if we try this:

    plt.setp(axes.spines.values())
    

    we see that this does return possible arguments. So in summary, changing plt.setp(axes.spines, visible=False) to plt.setp(axes.spines.values(), visible=False) will remove all spines since it is iterating through the objects and not the keys.

    Full code:

    import matplotlib.pyplot as plt
    
    x = range(0,10)
    y = [i*i for i in x]
    
    plt.plot(x,y) #Plotting x against y
    axes = plt.gca() #Getting the current axis
    
    axes.spines['top'].set_visible(False)
    
    plt.setp(axes.spines.values(), visible=False) 
    
    plt.show() #Showing the plot