Py.Cafe

antonymilne/

palettes-new

Advanced Data Visualizations with Plotly and Vizro

DocsPricing
  • 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
# 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 plotly.graph_objects as go
import vizro.models as vm
import vizro.plotly.express as px
from vizro import Vizro
from vizro.figures import kpi_card, kpi_card_reference
from vizro.models._components.form._text_area import TextArea
from vizro.models._components.form._user_input import UserInput
from vizro.models.types import capture
from vizro.tables import dash_ag_grid
from vizro.themes import palettes

iris = px.data.iris()
tips = px.data.tips()
stocks = px.data.stocks(datetimes=True)
gapminder_2007 = px.data.gapminder().query("year == 2007")
df_kpi = pd.DataFrame({"Actual": [100, 200, 700], "Reference": [100, 300, 500], "Category": ["A", "B", "C"]})

waterfall_data = pd.DataFrame(
    {
        "x": [
            "Sales",
            "Consulting",
            "Net revenue",
            "Purchases",
            "Other expenses",
            "Profit before tax",
        ],
        "y": [60, 80, 0, -40, -20, 0],
        "measure": [
            "relative",
            "relative",
            "total",
            "relative",
            "relative",
            "total",
        ],
    }
)

@capture("graph")
def waterfall(data_frame: pd.DataFrame, x: str, y: str, measure: list[str]):
    """Custom waterfall chart."""
    fig = go.Figure(
        data=go.Waterfall(
            x=data_frame[x],
            y=data_frame[y],
            measure=data_frame[measure],
            showlegend=False,
        ),
    )
    fig.update_layout(showlegend=False)
    return fig


@capture("graph")
def sankey(data_frame: pd.DataFrame, source: str, target: str, value: str):
    """Custom Sankey diagram."""
    fig = go.Figure(
        data=[
            go.Sankey(
                node={"label": ["A1", "A2", "B1", "B2", "C1", "C2"]},
                link={
                    "source": [0, 1, 0, 2, 3, 3],  # indices correspond to labels, eg A1, A2, A1, B1, ...
                    "target": [2, 3, 3, 4, 4, 5],
                    "value": [8, 4, 2, 8, 4, 2],
                },
            )
        ]
    )
    return fig


graphs = vm.Page(
    title="Graphs",
    layout=vm.Grid(grid=[[0, 1, 2], [3, 4, 5], [6, 7, 8]]),
    components=[
        vm.Graph(
            figure=px.scatter(
                gapminder_2007,
                x="gdpPercap",
                y="lifeExp",
                size="pop",
                size_max=60,
                color="continent",
            )
        ),
        vm.Graph(figure=px.box(tips, y="total_bill", x="day", color="day")),
        vm.Graph(figure=px.histogram(tips, x="total_bill")),
        vm.Graph(
            figure=px.histogram(
                tips,
                y="day",
                x="total_bill",
                color="sex",
                barmode="group",
                orientation="h",
            )
        ),
        vm.Graph(figure=px.density_heatmap(tips, x="day", y="size", z="tip", histfunc="avg", text_auto="$.2f")),
        vm.Graph(figure=px.histogram(tips, x="sex", y="total_bill", color="day")),
        vm.Graph(figure=waterfall(waterfall_data, x="x", y="y", measure="measure")),
        vm.Graph(figure=px.pie(tips, values="tip", names="day", hole=0.85)),
        vm.Graph(
            figure=px.bar(
                gapminder_2007.query("country.isin(['United States', 'Pakistan', 'India', 'China', 'Indonesia'])"),
                x="pop",
                y="country",
                orientation="h",
            )
        ),
    ],
)

sankey_page = vm.Page(
    title="Sankey",
    components=[
        vm.Graph(
            title="Energy flow",
            figure=sankey(pd.DataFrame(), source="source", target="target", value="value"),
            footer="Sample energy flow from sources to sectors.",
        ),
    ],
)

# DASHBOARD -------------------------------------------------------------------
dashboard = vm.Dashboard(
    pages=[
        graphs,
    ],
)

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