简体   繁体   中英

Adding a slider to figure with subplots in plotly

I am trying to use plotly to show how 4 different functions change as one of their common parameters changes. I want 4 stacked subplots (one for each function) with a slider bar underneath it for that changing parameter. Essentially I'm hoping that it looks something like the Subplots with Shared X-Axes example on this page , except with a slider like the one shown here underneath it. This page looks deceptively similar to what I need, except that I don't want a range slider here. This is not the actual code I'm using, but I'll post some code similar to mine in structure for convenience:

def f(rho):
    dom = np.linspace(0, 1, 50)
    f1 = (dom - rho) ** 2
    f2 = np.sin(dom * rho)
    f3 = np.abs(dom - rho)
    f4 = dom ** rho
    return f1, f2, f3, f4

I want to see how these 4 functions change with rho in np.linspace(0.5, 2, 101) , so rho is the variable controlled by the slider. I like plotly because of some customizations I'd like to do and the ability to scroll over a figure to see function values.

I eventually found this post on the plotly community forums, which answers the question with the following code example:

import plotly.graph_objs as go
from plotly.tools import make_subplots

fig = make_subplots(1, 2)

fig.add_scatter(y=[1, 3, 2], row=1, col=1, visible=True)
fig.add_scatter(y=[3, 1, 1.5], row=1, col=1, visible='legendonly')
fig.add_scatter(y=[2, 2, 1], row=1, col=1, visible='legendonly')
fig.add_scatter(y=[1, 3, 2], row=1, col=2, visible=True)
fig.add_scatter(y=[1.5, 2, 2.5], row=1, col=2, visible='legendonly')
fig.add_scatter(y=[2.5, 1.2, 2.9], row=1, col=2, visible='legendonly')

steps = []
for i in range(3):
    step = dict(
        method = 'restyle',  
        args = ['visible', ['legendonly'] * len(fig.data)],
    )
    step['args'][1][i] = True
    step['args'][1][i+3] = True
    steps.append(step)

sliders = [dict(
    steps = steps,
)]

fig.layout.sliders = sliders

go.FigureWidget(fig)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM