1 year ago

#387602

test-img

terraregina

Button incrementing a single step in plotly.express slider

I have a graph with multiple subplots controlled by the same slider created with plotly and plotly.express.

Is it possible to add a button of some sort that increments the slider value by 1 and updates all the graphs? Example graph code is provided below with two subplots where the slider iterates over the values of the variable "trial".

I have 5 subplots controlled in this manner over a range of 600 trials and it will be very useful if I could have a more controlled incrementor where I click the button and move the slider a single trial forward and all the graphs are updated.

import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go


# Example Data for plot A
t = 10
npi = 8
nc = 4
data = np.zeros([npi,nc,t])
for c in range(nc):
    data[:,c,:] = np.tile(np.arange(npi).reshape(npi,1),t) +     np.random.normal(0,2,size=[npi,t])

pols = np.arange(npi)
ts = np.arange(t)
cs = np.arange(nc)

mi = pd.MultiIndex.from_product([pols, cs, ts], names=['policy', 'context', 'trial'])
df = pd.Series(index=mi, data=data.flatten())
df = df.reset_index().rename(columns = {0:'probability'})

# Desired animation for plot A
fig1 = px.line(df, x='policy', y='probability',animation_frame='trial',animation_group='context', color="context")



# Example Data for plot B
t = 10
nc = 6
tau = 4
data = np.zeros([nc,tau,t])
for ti in range(tau):
    data[:,ti,:] = np.tile(np.arange(nc).reshape(nc,1),t) + np.random.normal(0,2,size=[nc,t])

conts = np.arange(nc)
ts = np.arange(t)
taus = np.arange(tau)

mi = pd.MultiIndex.from_product([conts, taus, ts], names=['context', 'timepoint', 'trial'])
df = pd.Series(index=mi, data=data.flatten())
df = df.reset_index().rename(columns = {0:'probability'})

# Desired animation for plot B
fig2 = px.line(df, x='context', y='probability',animation_frame='trial',animation_group='timepoint', color="timepoint")



### combined graph
# integrate the two figures, putting second figure on separate axis
fig = go.Figure(
    data=[t for t in fig1.data] + [t.update(xaxis="x2", yaxis="y2") for t in fig2.data],
    frames=[
        go.Frame(
            name=fr1.name,
            data=[t for t in fr1.data]
            + [t.update(xaxis="x2", yaxis="y2") for t in fr2.data],
        )
        for fr2, fr1 in zip(fig2.frames, fig1.frames)
    ],
    layout=fig1.layout,
)

# now config axes appropriately
fig.update_layout(
    xaxis_domain=[0, 0.49],
    xaxis2={"domain": [0.51, 1], "matches": None, "title":{"text":fig2.layout.xaxis.title.text}},
    yaxis2={"matches":"y"},
    showlegend=False,
)

P.S. The example was copied over from an answer by another user from a previous question I had asked. I am not sure if there is any community guidelines about this but will adapt as necessary if this is flagged in some way.

python

button

plotly

slider

0 Answers

Your Answer

Accepted video resources