Py.Cafe

huong-li-nguyen/

vizro-life-expectancy-asia

Southeast Asia Life Expectancy Visualization

DocsPricing
  • assets/
  • app.py
  • 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# Vizro is an open-source toolkit for creating modular data visualization applications.
# check out https://github.com/mckinsey/vizro for more info about Vizro
# and checkout https://vizro.readthedocs.io/en/stable/ for documentation.

import vizro.plotly.express as px
import vizro.models as vm
import vizro.actions as va
from vizro.models.types import capture
from vizro import Vizro

SELECTED_COUNTRIES = [
    "Singapore",
    "Malaysia",
    "Thailand",
    "Indonesia",
    "Philippines",
    "Vietnam",
    "Cambodia",
    "Myanmar",
    "NONE"
]

gapminder = px.data.gapminder().query("country.isin(@SELECTED_COUNTRIES)")


@capture("graph")
def bump_chart(data_frame, highlight_country=None):
    data_with_rank = data_frame.copy()
    data_with_rank['rank'] = data_frame.groupby('year')['lifeExp'].rank(
        method='dense', ascending=False
    )
    
    fig = px.line(
        data_with_rank,
        x="year",
        y="rank",
        color="country",
        markers=True,
    )
    
    fig.update_layout(
        legend_title="",
        xaxis_title="",
        yaxis=dict(autorange="reversed"),
        yaxis_title="Rank (1 = Highest lifeExp)",
    )
    
    if highlight_country:
        for trace in fig.data:
            if trace.name == highlight_country:
                trace.opacity = 1.0
                trace.line.width = 3
            else:
                trace.opacity = 0.3
                trace.line.width = 2
    
    return fig


@capture("graph")
def bar_chart(data_frame):
    fig = px.bar(
        data_frame[data_frame["year"] == 2007],
        y="country", 
        x="lifeExp",
    )
    fig.update_layout(yaxis_title="", xaxis_title="lifeExp (2007)")
    return fig


page = vm.Page(
    title="Cross-highlighting example",
    components=[
        vm.Graph(
            figure=bar_chart(data_frame=gapminder),
            header="💡 Click on any bar to highlight that country's trace in the bump chart",
            actions=[va.set_control(control="highlight_country_parameter", value="y")],
        ),
        vm.Graph(id="bump_chart", figure=bump_chart(data_frame=gapminder)),
    ],
    controls=[
        vm.Filter(column="year"),
        vm.Parameter(
            id="highlight_country_parameter",
            targets=["bump_chart.highlight_country"],
            selector=vm.Dropdown(multi=False, options=SELECTED_COUNTRIES, value="NONE"),
        ),
    ]
)

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