I have a simple function which plots a horizontal line to a certain value of x that is defined in a function as shown below:
def plot_lines(x):
plt.hlines(y = 10,
xmin = 0,
xmax = x)
plt.xlim(0, 10)
plt.show()
Using ipywidgets, I can get a slider where x is the value I interact with. It looks as follows
from ipywidgets import *
x = widgets.IntSlider(value = 2,
min = 0,
max = 10,
)
interact(plot_lines, x = x)
My output looks as follows: I can drag along the slider to change the value of x. As a result, the plot changes accordingly.
I defined a function plot_lines
here and the argument that I pass x
acts as an interactive parameter.
I am relatively new to Plotly. Is it possible to get a slider in a similar manner in Plotly? How would the equivalent implementation of this simple function look like in Plotly?
CodePudding user response:
Ok. I found the solution to this on my own:
def hlines(x):
fig1 = go.FigureWidget()
fig1.add_hline(y = 10,
x0 = 0,
#Normalize value for x between min and max
x1 = x,
line_color = "blue"
)
#Update ranges for x and y axis
fig1.update_xaxes(range=[0, 10])
fig1.update_yaxes(range=[0, 15])
fig1.show()
#x takes normalized value.
interact(hlines, x = 0.5)
One thing to be noted is that in Plotly, it seems the x is taking normalized value between min and max in the xaxes.
CodePudding user response:
There are options
native plotly
- use rangeslider
import numpy as np
import plotly.express as px
fig = px.line(x=np.linspace(1,10,20), y=np.sin(np.linspace(1,10,20)))
fig.update_layout(xaxis={"rangeslider":{"autorange":True}, "range":[1,5]})
ipywidgets
- update xaxis range
import numpy as np
import plotly.express as px
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
def widget_slider(x):
return fig.update_layout(xaxis_range=[1,x])
fig = px.line(x=np.linspace(1,10,20), y=np.sin(np.linspace(1,10,20)))
interact(widget_slider, x=widgets.IntSlider(min=1, max=10, step=1, value=5))