mckinsey / vizro

Vizro is a toolkit for creating modular data visualization applications.
https://vizro.readthedocs.io/en/stable/
Apache License 2.0
2.46k stars 109 forks source link

Dynamically Update Parameter Options Based on Another Parameter's Value #542

Open reouvenzana opened 1 week ago

reouvenzana commented 1 week ago

Question

Hello!

Basically, the title : Parameter A modifies the options avalables in Parameter B.

It's a classical dashboard use case, and I'm sure it's possible somehow (it is in Dash), but it doesn't seem covered in the documentation, or at least, explicitly covered.

I first tried to approach the problem with a capture decorator, but it doesn't apply to parameters. Hence, I'm not sure how to handle this use case.

Sorry if I missed something.

Code/Examples

No response

Other information

No response

Which package?

vizro

Package version

No response

Python version

No response

OS

No response

Code of Conduct

petar-qb commented 5 days ago

Hi @reouvenzana 👋 and thanks for the great question. This is a well-known feature that we already have on our list.

In one of the next releases, along with some other required improvements, we will document how this example can be configured using Vizro custom actions. Until we finalise the required improvements and the aforementioned explanation, here is an example of how you should already be able to achieve the desired case.

"""Dev app to try things out."""

import pandas as pd
from dash import Input, Output, callback
import vizro.models as vm
import vizro.plotly.express as px
from vizro import Vizro
from vizro.models.types import capture

df = px.data.iris()

vm.Page.add_type("controls", vm.RadioItems)

page = vm.Page(
    title="Page Title",
    components=[
        vm.Graph(
            id="graph_1",
            figure=px.scatter(df, x=None, y="sepal_length", color="species"),
        )
    ],
    controls=[
        vm.RadioItems(
            title="Select item:",
            id="item_selector",
            options=["sepal", "petal"],
            value="sepal",
        ),
        vm.Parameter(
            targets=["graph_1.x"],
            selector=vm.Dropdown(
                title="Select x:",
                id="x_selector",
                multi=False,
                options=["sepal_width", "sepal_length"],
                value="sepal_width"
            )
        )
    ]
)

dashboard = vm.Dashboard(pages=[page])

# Pure dash callback to update x_selector options based on item_selector value
@callback(
    Output("x_selector", "options"),
    Output("x_selector", "value"),
    Input("item_selector", "value")
)
def update_parameter_options(selected_item):
    if selected_item == "sepal":
        options = ["sepal_width", "sepal_length"]
    else:
        options = ["petal_width", "petal_length"]
    return options, options[0]

if __name__ == "__main__":
    Vizro().build(dashboard).run()