'Plotly adding two sliders in python
I have read plotly slider instruction:https://plotly.com/python/sliders/, but still can't find a way to create two sliders in one graph. I'm new to plotly so any kind of advice will be helpful.
Solution 1:[1]
Apparently it's not possible (see plotly community post) - but since this post is from '18, there might be a solution by now (that I'm not aware of). If you are working in a Jupyter notebook, you could use FigureWidget (as suggested in the post) as follows:
import plotly.graph_objects as go
import numpy as np
def linear_function(a,b,x):
return a*x+b
a0 = 0.1
b0 = 0.1
x = np.arange(-10,10,0.1)
data = [go.Scatter(x=x,y=linear_function(a=a0,b=b0,x=x))]
fig = go.FigureWidget(data=data)
fig.update_yaxes(autorange=False,range=(-3,3))
@interact(a=(0, 1, 0.1), b=(0, 1, 0.1))
def update(a=a0, b=b0):
with fig.batch_update():
fig.data[0].y = linear_function(a=a,b=b,x=x)
return fig
However, there is sometimes a significant delay in rendering when using interact. Therefore, I would like to point out that in many cases it may be the better solution to fix one variable and only set the other variable interactively:
# Fixing a
a = 0.1
fig = go.Figure()
fig.update_layout(title = f"Linear function a*x+b with a fixed at {a} and b adjustable")
fig.update_yaxes(autorange=False,range=(-3,3))
parameters = np.arange(0, 5, 0.1)
for b in parameters:
fig.add_trace(
go.Scatter(
visible=False,
x=x,
y=linear_function(a=a,b=b,x=x),
))
# Make 0th trace visible
fig.data[0].visible = True
# Create and add slider
steps = []
for i in range(len(fig.data)):
step = dict(
method="update",
label=f"{parameters[i]: .2f}",
args=[{"visible": [False] * len(fig.data)}],
)
step["args"][0]["visible"][i] = True
steps.append(step)
sliders = [dict(
active=0,
pad={"t": 50},
steps=steps
)]
fig.update_layout(
sliders=sliders
)
fig.show()
I hope this helped!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jrnp |
