pythonmatplotlibinteractivematplotlib-widget

Set tick labels for matplotlib Slider widgets


The slider behavior in matplotlib has changed with recent updates. With the following code:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

fig = plt.figure(figsize=(8, 4))
ax_main = plt.axes([0.15, 0.3, 0.7, 0.6])
ax_skal = plt.axes([0.2, 0.18, 0.65, 0.02], facecolor="lightgrey")

s_skal = Slider(ax_skal, 'time scale', 0.5, 2, valinit=1, valfmt='%0.1f')

#ax_skal.xaxis.set_visible(True)
sl_xticks = np.arange(0.6, 2, 0.2)
ax_skal.set_xticks(sl_xticks)

plt.show() 

we could generate in matplotlib 3.3.1 and earlier a slider object with tick labels. enter image description here

However, in matplotlib 3.5.1 the tick labels have disappeared.

enter image description here

The suggestion in this thread to set the x-axis to visible does not work, as the x-axis attribute visible is already True, as is the attribute in_layout. So, how can we set tick labels for slider objects?


Solution

  • As I spent some time on this problem, I thought I leave the answer here. Turns out the updated slider version hogs the axis space in which it is placed and removes the x- and y-axes with their spine objects from the list of artists used for rendering the layout. So, we have to add the x-axis object (or for vertical sliders the y-axis object) again to the axis after the creation of the slider object:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.widgets import Slider
    
    fig = plt.figure(figsize=(8, 4))
    ax_main = plt.axes([0.15, 0.3, 0.7, 0.6])
    ax_skal = plt.axes([0.2, 0.18, 0.65, 0.02], facecolor="lightgrey")
    
    s_skal = Slider(ax_skal, 'time scale', 0.5, 2, valinit=1, valfmt='%0.1f')
    
    ax_skal.add_artist(ax_skal.xaxis)
    sl_xticks = np.arange(0.6, 2, 0.2)
    ax_skal.set_xticks(sl_xticks)
    
    plt.show() 
    

    Sample output: enter image description here