1

I'm trying to put a slider right under the x-axis of a subplot in matplotlib, so that both start and end at the same value. Is there an easy way to do that, meaning that I don't have to find the right coordinates and put them myself when I create the plt.axe containing the slider?

Antys
  • 49
  • 1
  • 6
  • 2
    like [in this demo](https://matplotlib.org/3.1.1/gallery/widgets/slider_demo.html)? – scleronomic Feb 14 '20 at 09:23
  • @scleronomic Yes, exactly. In the demo, the coordinates for the axis are set by hand, and I want to know if there is a way to do that without finding the coordinates by hand. – Antys Feb 14 '20 at 21:37

1 Answers1

2

You could use ax.get_position() to get x0, y0, width and height of the axis and use this to define the positions for the axes of the slider.

I adapted the matplotlib example to show a use case:

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

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.3)
t = np.arange(0.0, 1.0, 0.001)
a0 = 5
f0 = 3
delta_f = 5.0
s = a0 * np.sin(2 * np.pi * f0 * t)
l, = plt.plot(t, s, lw=2)
ax.margins(x=0)

axcolor = 'lightgoldenrodyellow'

def xaligned_axes(ax, y_distance, width, **kwargs):
    return plt.axes([ax.get_position().x0,
                     ax.get_position().y0-y_distance,
                     ax.get_position().width, width],
                    **kwargs)

axfreq = xaligned_axes(ax=ax, y_distance=0.1, width=0.03, facecolor=axcolor)
axamp = xaligned_axes(ax=ax, y_distance=0.15, width=0.03, facecolor=axcolor)

sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0, valstep=delta_f)
samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)

def update(val):
    amp = samp.val
    freq = sfreq.val
    l.set_ydata(amp*np.sin(2*np.pi*freq*t))
    fig.canvas.draw_idle()

sfreq.on_changed(update)
samp.on_changed(update)

But as you have to use plt.subplots_adjust(bottom=0.3) to have enough space below the plot and you need to define the width and the distance to the axis in y direction I guess you do not win that much.

scleronomic
  • 4,392
  • 1
  • 13
  • 43