Py.Cafe

huong-li-nguyen/

vizro-tips-analysis-1

Sex-Based Tips Analysis

DocsPricing
  • assets/
  • yaml_version/
  • app.py
  • charts.py
  • data.yaml
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import vizro.actions as va
import vizro.models as vm
import vizro.plotly.express as px
from vizro import Vizro
from vizro.tables import dash_ag_grid
from vizro.models.types import capture

tips = px.data.tips()

# This function written by ChatGPT and could probably be better...
@capture("graph")
def highlighted_box(data_frame, highlight=None):
    # Dim all traces first
    fig = px.box(data_frame, x="tip", y="sex")
    for trace in fig.data:
        trace.opacity = 0.2

    if highlight is not None:
        # Overlay highlighted category
        df_highlight = data_frame[data_frame["sex"] == highlight]
        fig_highlight = px.box(
            df_highlight, x="tip", y="sex", color="sex"
        )
        for trace in fig_highlight.data:
            trace.opacity = 1.0   # make highlight fully visible
            fig.add_trace(trace)

    return fig

page = vm.Page(
    title="Cross-filter from graph to table",
    components=[
        vm.Graph(
            id="box",
            title="Click on a box to use that box's sex to filter table",
            figure=highlighted_box(tips),
            actions=[
                va.set_control(control="sex_filter", value="y"),
                va.set_control(control="highlight", value="y")
            ]
        ),
        vm.AgGrid(id="tips_table", figure=dash_ag_grid(tips)),  
    ],
    controls=[
        vm.Filter(id="sex_filter", column="sex", targets=["tips_table"]),
        # This parameter looks pretty silly, definitely you'd want to make it hidden in reality
        vm.Parameter(id="highlight", selector=vm.RadioItems(options=["NONE", "Male", "Female"]), targets=["box.highlight"])
    ],  
)

dashboard = vm.Dashboard(pages=[page])
Vizro().build(dashboard).run()