You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib交互式滑块绘图中Y轴自动缩放问题

解决交互式滑块调整时Y轴自动缩放问题

你的代码中,仅调用ax.autoscale()无法触发Y轴重新缩放的原因是:该方法只是设置轴的自动缩放模式,不会主动重新计算当前数据的边界并更新视图。需要结合两个步骤来实现自动缩放:

  1. 调用ax.relim():重新计算当前绘图数据的边界范围
  2. 调用ax.autoscale_view():根据新的边界自动调整轴的显示范围

修改后的update函数如下:

def update(val):
    line.set_ydata(my_func(x, c_slider.val))
    ax.relim()  # 重新计算数据的上下限
    ax.autoscale_view()  # 自动适配Y轴范围
    fig.canvas.draw_idle()

完整的可运行代码:

import numpy as np
from matplotlib.widgets import Slider, Button
import matplotlib.pyplot as plt
%matplotlib notebook

# Define stuff
my_func = lambda x, c: x - c

# Make plot
x = np.arange(0, 50, 1)
c_init = 10
fig, ax = plt.subplots()
line, = ax.plot(x, my_func(x, c_init), lw=2)

# adjust the main plot to make room for the sliders
fig.subplots_adjust(left=0.25, bottom=0.25)

# Make a vertically oriented slider to control the stock volume
ax_c = fig.add_axes([0.1, 0.25, 0.0225, 0.63])
c_slider = Slider(
    ax=ax_c,
    label="My function",
    valmin=-100,
    valmax=100,
    valinit=c_init,
    orientation="vertical"
)

# The function to be called anytime a slider's value changes
def update(val):
    line.set_ydata(my_func(x, c_slider.val))
    ax.relim()
    ax.autoscale_view()
    fig.canvas.draw_idle()
    
# register the update function with each slider
c_slider.on_changed(update)

# Create a `matplotlib.widgets.Button` to reset the sliders to initial values.
resetax = fig.add_axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', hovercolor='0.975')

def reset(event):
    c_slider.reset()
button.on_clicked(reset)

plt.show()

这样调整滑块时,Y轴会根据当前函数的取值范围自动缩放,解决你遇到的问题。

内容的提问来源于stack exchange,提问作者spadel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 22:10:09