Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Change Custom Control Values in Plotly

I would like to change the Slider values from "Step 0, ..., Step 3" to the Date values within the "Dates" column "19/11/2019,..., 21/11/2019".

Besides that, slightly above the slider to the left is a counter that shows the "Frequency: Steps X", instead of "Steps X", I would like that to be changed it to dynamically display "Dates X", where X shows the column values from the "Dates" column.

This is my dataset

+------------+---+---+---+---+
|    Date    | A | B | C | D |
+------------+---+---+---+---+
| 19/11/2012 | 1 | 3 | 4 | 5 |
| 20/11/2012 | 3 | 2 | 3 | 2 |
| 21/11/2012 | 1 | 2 | 2 | 2 |
+------------+---+---+---+---+

Here is my code.

# imports
import plotly.graph_objects as go
import pandas as pd

# sample data
dat=pd.DataFrame(dict(Date=['19/11/2012', '20/11/2012', '21/11/2012'],
                    A=[1,3,1],
                    B=[3,2,2],
                    C=[4,3,2],
                    D=[5,2,2],))

# Create figure
fig = go.Figure()

# Add traces, one for each slider step
for step in np.arange(len(dat['Date'])):
    fig.add_trace(
        go.Scatter(
            visible=False,
            line=dict(color="#00CED1", width=6),
            name="𝜈 = " + str(step),
            x=['A','B','C','D'],
            y=dat.iloc[step,1::]))

# Make 10th trace visible


# Create and add slider
steps = []
for i in range(len(fig.data)):
    step = dict(
        method="restyle",
        args=["visible", [False] * len(fig.data)],
    )
    step["args"][1][i] = True  # Toggle i'th trace to "visible"
    steps.append(step)

sliders = [dict(
    active=1,
    currentvalue={"prefix": "Frequency: "},
    pad={"t": 50},
    steps=steps
)]

fig.update_layout(
    sliders=sliders
)

fig.show()

This is the output of my code: This is the output of my code

As you can see, the circled part is the "Frequency: Step X" counter and the pointed parts are the Slider.

like image 736
crickcrock Avatar asked Aug 16 '26 08:08

crickcrock


2 Answers

This should do it:

# Edit slider labels
fig['layout']['sliders'][0]['currentvalue']['prefix']='Date: '
for i, date in enumerate(dat['Date'], start = 0):
    fig['layout']['sliders'][0]['steps'][i]['label']=date

Plot:

enter image description here

Code:

dat=pd.DataFrame(dict(Date=['19/11/2012', '20/11/2012', '21/11/2012'],
                    A=[1,3,1],
                    B=[3,2,2],
                    C=[4,3,2],
                    D=[5,2,2],))

# Create figure
fig = go.Figure()

# Add traces, one for each slider step
for step in np.arange(len(dat['Date'])):
    fig.add_trace(
        go.Scatter(
            visible=False,
            line=dict(color="#00CED1", width=6),
            name="𝜈 = " + str(step),
            x=['A','B','C','D'],
            y=dat.iloc[step,1::]))

# Create and add slider
steps = []
for i in range(len(fig.data)):
    step = dict(
        method="restyle",
        args=["visible", [False] * len(fig.data)],
    )
    step["args"][1][i] = True  # Toggle i'th trace to "visible"
    steps.append(step)

sliders = [dict(
    active=1,
    currentvalue={"prefix": "Frequency: "},
    pad={"t": 50},
    steps=steps
)]

fig.update_layout(
    sliders=sliders
)

# Edit slider labels
fig['layout']['sliders'][0]['currentvalue']['prefix']='Date: '
for i, date in enumerate(dat['Date'], start = 0):
    fig['layout']['sliders'][0]['steps'][i]['label']=date

fig.show()
like image 161
vestland Avatar answered Aug 17 '26 23:08

vestland


You can simply change the sliders and step attributes. This avoids unnecessary loops in the code!

  • To change the prefix, modify the 'currentvalue' attribute of the slider:

currentvalue = {"prefix": "Date: "}

Example:

sliders = [dict(
               active=1,
               currentvalue={"prefix": "Date: "},
               pad={"t": 50},
               steps=steps 
          )]
  • To change the step name, modify the 'label' attribute of the step:

label = dat['Date'][i]

Example:

step = dict(
            method="restyle",
            args=["visible", [False] * len(fig.data)],
            label=dat['Date'][i]
            )

Output image: Output image with dates

Full code:

# imports
import plotly.graph_objects as go
import pandas as pd

# sample data
dat=pd.DataFrame(dict(Date=['19/11/2012', '20/11/2012', '21/11/2012'],
                    A=[1,3,1],
                    B=[3,2,2],
                    C=[4,3,2],
                    D=[5,2,2],))

# Create figure
fig = go.Figure()

# Add traces, one for each slider step
for step in np.arange(len(dat['Date'])):
    fig.add_trace(
        go.Scatter(
            visible=False,
            line=dict(color="#00CED1", width=6),
            name="𝜈 = " + str(step),
            x=['A','B','C','D'],
            y=dat.iloc[step,1::]))

# Make 10th trace visible


# Create and add slider
steps = []
for i in range(len(fig.data)):
    step = dict(
        method="restyle",
        args=["visible", [False] * len(fig.data)],
        label=dat['Date'][i]
    )
    step["args"][1][i] = True  # Toggle i'th trace to "visible"
    steps.append(step)

sliders = [dict(
    active=1,
    currentvalue={"prefix": "Date: "},
    pad={"t": 50},
    steps=steps
)]

fig.update_layout(
    sliders=sliders
)

fig.show()
like image 39
lmonari Avatar answered Aug 17 '26 21:08

lmonari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!