Py.Cafe

huong-li-nguyen/

figure-friday-week-37

Visualizing Under-Five Mortality Rates by Country

DocsPricing
  • assets/
  • data/
  • 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# 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 pandas as pd
import vizro.models as vm
import vizro.plotly.express as px
from vizro import Vizro
from vizro._themes._color_values import COLORS
from vizro.models.types import capture
from vizro.tables import dash_ag_grid

mortality_df = pd.read_csv("data/child-mortality.csv")
mortality_df["Quintiles"] = pd.qcut(mortality_df["Under-five mortality rate"], 5, labels=False)
mortality_df = mortality_df.sort_values('Year', ascending=True)

@capture("graph")
def line(data_frame, **kwargs):
    """Plotly line chart with post-fig updates."""
    fig = px.line(data_frame, **kwargs)
    fig.update_layout(legend_title="", yaxis_ticksuffix="%", xaxis_showgrid=False, yaxis_rangemode='nonnegative')
    return fig

@capture("graph")
def choropleth(data_frame, **kwargs):
    df_filtered = data_frame[data_frame['Year'] % 5 == 0]
    fig = px.choropleth(data_frame=df_filtered, **kwargs)
    fig.update_layout({"margin": {"t": 0, "b": 0, "r": 0, "l": 0}})
    fig.update_coloraxes(colorbar_ticksuffix="%")
    return fig


CELL_STYLE = {
    "styleConditions": [
        {
            "condition": "params.data.Quintiles == 4",
            "style": {"backgroundColor": "#7e000c"},
        },
        {
            "condition": "params.data.Quintiles == 3",
            "style": {"backgroundColor": "#a1423a"},
        },
        {
            "condition": "params.data.Quintiles == 2",
            "style": {"backgroundColor": "#c2736b"},
        },
        {
            "condition": "params.data.Quintiles == 1",
            "style": {"backgroundColor": "#dea4a1"},
        },
        {
            "condition": "params.data.Quintiles == 0",
            "style": {"backgroundColor": "#f8d6da"},
        },
    ],
}

COLUMNDEFS = [
    {"field": "Entity", "cellDataType": "text"},
    {"field": "Code", "cellDataType": "text"},
    {"field": "Year", "cellDataType": "text"},
    {
        "field": "Under-five mortality rate",
        "headerName": "Under-five mortality rate in %",
           "valueFormatter": {"function": "d3.format(',.1f')(params.value)"},
           "cellStyle": CELL_STYLE
    },
]

chart_page = vm.Page(
    title="Chart  πŸ“ˆ",
    id="chart",
    components=[
        vm.Graph(
            figure=line(
                data_frame=mortality_df,
                x="Year",
                y="Under-five mortality rate",
                color="Entity",
            ),
            title="Under-five child mortality rate by country",
            header="""
                 The estimated share of newborns who die before reaching the age of five.
                 """,
            footer="""
            **Data source:** Data source: UN IGME (2023); Gapminder (2015). [Learn more about this data](https://www.gapminder.org/data/documentation/gd005/).
            """,
        )
    ],
    controls=[
        vm.Filter(column="Year"),
        vm.Filter(
            column="Entity",
            selector=vm.Dropdown(
                title="Countries and Regions",
                value=["Brazil", "India", "United States", "France", "United Kingdom", "Sweden"],
            ),
        ),
    ],
)

map_page = vm.Page(
    title="Map πŸ“",
    id="map",
    components=[
        vm.Graph(
            figure=choropleth(
                data_frame=mortality_df,
                locations="Code",
                hover_name="Entity",
                color="Under-five mortality rate",
                color_continuous_scale=COLORS["SEQUENTIAL_RED"],
                animation_frame="Year",
            ),
            title="Under-five child mortality rate by country",
            header="""
                 The estimated share of newborns who die before reaching the age of five.
                 """,
            footer="""
            **Data source:** Data source: UN IGME (2023); Gapminder (2015). [Learn more about this data](https://www.gapminder.org/data/documentation/gd005/).
            """,
        )
    ],
)

table_page = vm.Page(
    title="Table πŸ“‘",
    id="table",
    components=[
        vm.AgGrid(
            figure=dash_ag_grid(mortality_df, columnSize="responsiveSizeToFit", columnDefs=COLUMNDEFS),
            title="Under-five child mortality rate by country",
            header="""
                 The estimated share of newborns who die before reaching the age of five.
                 """,
            footer="""
            **Data source:** Data source: UN IGME (2023); Gapminder (2015). [Learn more about this data](https://www.gapminder.org/data/documentation/gd005/).
            """,
        )
    ],
    controls=[
        vm.Filter(column="Year"),
        vm.Filter(
            column="Entity",
            selector=vm.Dropdown(title="Countries and Regions"),
        ),
    ],
)


dashboard = vm.Dashboard(
    pages=[chart_page, map_page, table_page],
    title="Figure Friday - Week 37",
    navigation=vm.Navigation(
        nav_selector=vm.NavBar(
            items=[
                vm.NavLink(pages=["chart"], icon="Show Chart", label="Chart"),
                vm.NavLink(pages=["map"], icon="Globe", label="Map"),
                vm.NavLink(pages=["table"], icon="Table", label="Table"),
            ]
        )
    ),
    theme="vizro_light",
)

Vizro().build(dashboard).run()