Plotly单滑块更新影响双子图问题求助
解决Plotly双滑块联动异常问题
你编写的Plotly脚本中,控制正弦曲线频率的滑块会意外改变高斯曲面,核心原因是滑块的update操作未指定目标轨迹的索引,默认会尝试更新所有轨迹的对应属性——Surface轨迹同样包含y属性,因此会被频率滑块的y更新操作误影响。
修复方案
在每个滑块的步骤配置中,通过args的第三个参数指定要更新的轨迹索引(正弦曲线是第0个轨迹,高斯曲面是第1个轨迹),确保每个滑块仅操作对应轨迹的目标属性;同时修正原代码中active参数的计算错误,保证初始滑块位置正确:
import plotly.graph_objects as go from plotly.subplots import make_subplots import numpy as np # Create subplots fig = make_subplots(rows=1, cols=2, specs=[[{"type": "scatter"}, {"type": "surface"}]]) # Initial values xx = np.linspace(0, 2 * np.pi, 1000) initial_frequency = 1 initial_std = 1 # Initial plot of sine wave sine_trace = go.Scatter(x=xx, y=np.sin(initial_frequency * xx)) fig.add_trace(sine_trace, row=1, col=1) # Initial plot of 2D Gaussian x_gaussian = np.linspace(-5, 5, 100) y_gaussian = np.linspace(-5, 5, 100) X, Y = np.meshgrid(x_gaussian, y_gaussian) z_gaussian = np.exp(-(X**2 + Y**2) / (2 * initial_std**2)) / (2 * np.pi * initial_std**2) gaussian_trace = go.Surface(x=x_gaussian, y=y_gaussian, z=z_gaussian) fig.add_trace(gaussian_trace, row=1, col=2) # Create slider steps for frequency (sine wave) frequency_steps = [] for freq_val in np.arange(0.1, 5.1, 0.1): y_sine = np.sin(freq_val * xx) step1 = dict( method="update", args=[ {"y": [y_sine]}, # 更新正弦曲线的y值 {}, # 无需更新布局 [0] # 指定仅更新索引为0的轨迹(正弦曲线) ], label=str(freq_val) ) frequency_steps.append(step1) # Create slider steps for standard deviation (Gaussian surface) std_steps = [] for std_val in np.arange(0.1, 2.1, 0.1): z_std = np.exp(-(X**2 + Y**2) / (2 * std_val**2)) / (2 * np.pi * std_val**2) step = dict( method="update", args=[ {"z": [z_std]}, # 更新高斯曲面的z值 {}, # 无需更新布局 [1] # 指定仅更新索引为1的轨迹(高斯曲面) ], label=str(std_val) ) std_steps.append(step) std_slider = dict( active=int((initial_std - 0.1)/0.1), # 修正初始滑块位置索引 currentvalue={"prefix": "Std: "}, pad={"t": 50, "b": 10}, steps=std_steps, y=0.21, font={"size": 9} ) frequency_slider = dict( active=int((initial_frequency - 0.1)/0.1), # 修正初始滑块位置索引 currentvalue={"prefix": "Frequency: "}, pad={"t": 50, "b": 10}, steps=frequency_steps, y=0, font={"size": 9} ) fig.update_layout(sliders=[std_slider, frequency_slider]) fig.show()
内容的提问来源于stack exchange,提问作者Luca
相关产品推荐
相关产品推荐

