【问题标题】:Put a slider right under a subplot in matplotlib在 matplotlib 的子图下方放置一个滑块
【发布时间】:2020-02-14 07:36:05
【问题描述】:

我试图在 matplotlib 中的子图的 x 轴正下方放置一个滑块,以便以相同的值开始和结束。有没有一种简单的方法可以做到这一点,这意味着我在创建包含滑块的 plt.axe 时不必自己找到正确的坐标并放置它们?

【问题讨论】:

  • 喜欢in this demo?
  • @scleronomic 是的,完全正确。在演示中,轴的坐标是手动设置的,我想知道是否有办法做到这一点而无需手动找到坐标。
  • 这能解决您的问题吗?如果是这样,请考虑投票/接受答案:)

标签: python python-3.x matplotlib matplotlib-widget


【解决方案1】:

您可以使用ax.get_position() 获取轴的x0y0widthheight,并使用它来定义滑块轴的位置。

我调整了matplotlib example 来展示一个用例:

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)

但是由于您必须使用plt.subplots_adjust(bottom=0.3) 才能在绘图下方有足够的空间,并且您需要定义宽度和到 y 方向轴的距离,所以我猜您赢不了那么多。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 2017-08-01
    • 2017-04-22
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多