Spaces:
Running
Running
File size: 21,115 Bytes
8f9924d 01523fe 8f9924d fe13d0f 01523fe 2f4b096 01523fe fe13d0f |
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 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 |
"""Example app to show all features of Vizro."""
from time import sleep
from typing import List, Literal, Optional
import pandas as pd
import plotly.graph_objects as go
import vizro.models as vm
import vizro.plotly.express as px
from dash import dash_table, html, get_asset_url
import dash_bootstrap_components as dbc
from vizro import Vizro
from vizro.actions import export_data, filter_interaction
from vizro.models.types import capture
from vizro.tables import dash_ag_grid, dash_data_table
iris = px.data.iris()
tips = px.data.tips()
stocks = px.data.stocks(datetimes=True)
gapminder_2007 = px.data.gapminder().query("year == 2007")
waterfall_df = pd.DataFrame(
{
"measure": ["relative", "relative", "total", "relative", "relative", "total"],
"x": ["Sales", "Consulting", "Net revenue", "Purchases", "Other expenses", "Profit before tax"],
"text": ["+60", "+80", "", "-40", "-20", "Total"],
"y": [60, 80, 0, -40, -20, 0],
}
)
# HOME ------------------------------------------------------------------------
home = vm.Page(
title="Homepage",
layout=vm.Layout(grid=[[0, 1], [2, 3]], row_gap="16px", col_gap="24px"),
components=[
vm.Card(
text="""
![](assets/images/icons/line-chart.svg#icon-top)
### Components
Main components of Vizro include **charts**, **tables**, **cards**, **containers**,
**buttons** and **tabs**.
""",
href="/graphs",
),
vm.Card(
text="""
![](assets/images/icons/filters.svg#icon-top)
### Controls
Vizro has two different control types **Filter** and **Parameter**.
You can use any pre-existing selector inside the **Filter** or **Parameter**:
* Dropdown
* Checklist
* RadioItems
* RangeSlider
* Slider
* DatePicker
""",
href="/filters",
),
vm.Card(
text="""
![](assets/images/icons/download.svg#icon-top)
### Actions
Standard predefined actions are made available including **export data** and **filter interactions**.
""",
href="/export-data",
),
vm.Card(
text="""
![](assets/images/icons/use-case.svg#icon-top)
### Extensions
Vizro enables customization of **plotly express** and **graph object charts** as well as
creating custom components based on Dash.
""",
href="/custom-charts",
),
],
)
# COMPONENTS ------------------------------------------------------------------
graphs = vm.Page(
title="Graphs",
components=[
vm.Graph(
figure=px.scatter_matrix(
iris,
dimensions=["sepal_length", "sepal_width", "petal_length", "petal_width"],
color="species",
)
)
],
controls=[vm.Filter(column="species", selector=vm.Dropdown(title="Species"))],
)
ag_grid = vm.Page(
title="AG Grid",
components=[
vm.AgGrid(
title="Dash AG Grid", figure=dash_ag_grid(data_frame=gapminder_2007, dashGridOptions={"pagination": True})
)
],
controls=[vm.Filter(column="continent")],
)
table = vm.Page(
title="Table",
components=[
vm.Table(
title="Dash DataTable",
figure=dash_data_table(data_frame=gapminder_2007),
)
],
controls=[vm.Filter(column="continent")],
)
cards = vm.Page(
title="Cards",
components=[
vm.Card(
text="""
# Header level 1 <h1>
## Header level 2 <h2>
### Header level 3 <h3>
#### Header level 4 <h4>
"""
),
vm.Card(
text="""
### Paragraphs
Commodi repudiandae consequuntur voluptatum laborum numquam blanditiis harum quisquam eius sed odit.
Fugiat iusto fuga praesentium option, eaque rerum! Provident similique accusantium nemo autem.
Obcaecati tenetur iure eius earum ut molestias architecto voluptate aliquam nihil, eveniet aliquid.
Culpa officia aut! Impedit sit sunt quaerat, odit, tenetur error, harum nesciunt ipsum debitis quas.
"""
),
vm.Card(
text="""
### Block Quotes
>
> A block quote is a long quotation, indented to create a separate block of text.
>
"""
),
vm.Card(
text="""
### Lists
* Item A
* Sub Item 1
* Sub Item 2
* Item B
"""
),
vm.Card(
text="""
### Emphasis
This word will be *italic*
This word will be **bold**
This word will be _**bold and italic**_
"""
),
],
)
button = vm.Page(
title="Button",
layout=vm.Layout(grid=[[0], [0], [0], [0], [1]]),
components=[
vm.Graph(
figure=px.scatter(
iris,
x="sepal_width",
y="sepal_length",
color="species",
size="petal_length",
),
),
vm.Button(text="Export data", actions=[vm.Action(function=export_data())]),
],
controls=[vm.Filter(column="species", selector=vm.Dropdown(title="Species"))],
)
containers = vm.Page(
title="Containers",
components=[
vm.Container(
title="Container I",
layout=vm.Layout(grid=[[0, 1]]),
components=[
vm.Graph(
figure=px.scatter(
iris,
x="sepal_length",
y="petal_width",
color="species",
title="Container I - Scatter",
)
),
vm.Graph(
figure=px.bar(
iris,
x="sepal_length",
y="sepal_width",
color="species",
title="Container I - Bar",
)
),
],
),
vm.Container(
title="Container II",
components=[
vm.Graph(
figure=px.scatter(
iris,
x="sepal_width",
y="sepal_length",
color="species",
marginal_y="violin",
marginal_x="box",
title="Container II - Scatter",
)
)
],
),
],
)
tab_1 = vm.Container(
title="Tab I",
components=[
vm.Graph(
figure=px.bar(
gapminder_2007,
title="Graph 1",
x="continent",
y="lifeExp",
color="continent",
),
),
vm.Graph(
figure=px.box(
gapminder_2007,
title="Graph 2",
x="continent",
y="lifeExp",
color="continent",
),
),
],
)
tab_2 = vm.Container(
title="Tab II",
components=[
vm.Graph(
figure=px.scatter(
gapminder_2007,
title="Graph 3",
x="gdpPercap",
y="lifeExp",
size="pop",
color="continent",
),
),
],
)
tabs = vm.Page(title="Tabs", components=[vm.Tabs(tabs=[tab_1, tab_2])], controls=[vm.Filter(column="continent")])
# CONTROLS --------------------------------------------------------------------
filters = vm.Page(
title="Filters",
components=[
vm.Graph(
figure=px.scatter(
iris,
x="sepal_length",
y="petal_width",
color="species",
)
),
vm.Graph(
id="scatter_chart2",
figure=px.scatter(
iris,
x="petal_length",
y="sepal_width",
color="species",
),
),
],
controls=[
vm.Filter(column="species"),
vm.Filter(
column="petal_length",
targets=["scatter_chart2"],
selector=vm.RangeSlider(),
),
],
)
parameters = vm.Page(
title="Parameters",
components=[
vm.Graph(
id="scatter_chart_pm",
figure=px.scatter(
iris,
x="sepal_width",
y="sepal_length",
color="species",
size="petal_length",
color_discrete_map={"setosa": "#00b4ff", "versicolor": "#ff9222"},
),
),
vm.Graph(
id="bar_chart_pm",
figure=px.bar(
iris,
x="sepal_width",
y="sepal_length",
color="species",
color_discrete_map={"setosa": "#00b4ff", "versicolor": "#ff9222"},
),
),
],
controls=[
vm.Parameter(
targets=["scatter_chart_pm.color_discrete_map.virginica", "bar_chart_pm.color_discrete_map.virginica"],
selector=vm.Dropdown(options=["#ff5267", "#3949ab"], multi=False, value="#3949ab"),
)
],
)
selectors = vm.Page(
title="Selectors",
layout=vm.Layout(grid=[[0], [1], [1], [1], [2], [2], [2], [3], [3], [3]], row_min_height="170px", row_gap="24px"),
components=[
vm.Card(
text="""
A selector can be used within the **Parameter** or **Filter** component to allow the user to select a value.
The following selectors are available:
* Dropdown (**categorical** multi and single option selector)
* Checklist (**categorical** multi option selector only)
* RadioItems (**categorical** single option selector only)
* RangeSlider (**numerical** multi option selector only)
* Slider (**numerical** single option selector only)
* DatePicker(**temporal** multi and single option selector)
"""
),
vm.Table(
id="table-gapminder",
figure=dash_data_table(data_frame=gapminder_2007, page_size=10),
title="Gapminder Data",
),
vm.Table(id="table-tips", figure=dash_data_table(data_frame=tips, page_size=10), title="Tips Data"),
vm.Graph(
id="graph-stocks",
figure=px.line(stocks, x="date", y="GOOG", title="Stocks Data"),
),
],
controls=[
vm.Filter(
targets=["table-gapminder"],
column="lifeExp",
selector=vm.RangeSlider(title="Range Slider (Gapminder - lifeExp)", step=1, marks=None),
),
vm.Filter(
targets=["table-gapminder"],
column="continent",
selector=vm.Checklist(title="Checklist (Gapminder - continent)"),
),
vm.Filter(
targets=["table-gapminder"],
column="country",
selector=vm.Dropdown(title="Dropdown (Gapminder - country)"),
),
vm.Filter(
targets=["table-tips"],
column="day",
selector=vm.Dropdown(title="Dropdown (Tips - day)", multi=False, value="Sat"),
),
vm.Filter(
targets=["table-tips"],
column="sex",
selector=vm.RadioItems(title="Radio Items (Tips - sex)"),
),
vm.Filter(
targets=["table-tips"],
column="size",
selector=vm.Slider(title="Slider (Tips - size)", step=1, value=2),
),
vm.Filter(targets=["graph-stocks"], column="date", selector=vm.DatePicker(title="Date Picker (Stocks - date)")),
],
)
# ACTIONS ---------------------------------------------------------------------
export_data_action = vm.Page(
title="Export data",
components=[
vm.Graph(figure=px.scatter(iris, x="petal_length", y="sepal_length", color="species")),
vm.Graph(figure=px.histogram(iris, x="petal_length", color="species")),
vm.Button(text="Export data", actions=[vm.Action(function=export_data())]),
],
controls=[vm.Filter(column="species")],
)
chart_interaction = vm.Page(
title="Chart interaction",
components=[
vm.Graph(
figure=px.box(
gapminder_2007,
x="continent",
y="lifeExp",
color="continent",
custom_data=["continent"],
),
actions=[vm.Action(function=filter_interaction(targets=["scatter_relation_2007"]))],
),
vm.Graph(
id="scatter_relation_2007",
figure=px.scatter(
gapminder_2007,
x="gdpPercap",
y="lifeExp",
size="pop",
color="continent",
),
),
],
)
# CUSTOM CHARTS ------------------------------------------------------------------
@capture("graph")
def scatter_with_line(data_frame, x, y, hline=None, title=None):
"""Custom scatter chart based on px."""
fig = px.scatter(data_frame=data_frame, x=x, y=y, title=title)
fig.add_hline(y=hline, line_color="orange")
return fig
@capture("graph")
def waterfall(data_frame, measure, x, y, text, title=None): # noqa: PLR0913
"""Custom waterfall chart based on go."""
fig = go.Figure()
fig.add_traces(
go.Waterfall(
measure=data_frame[measure],
x=data_frame[x],
y=data_frame[y],
text=data_frame[text],
decreasing={"marker": {"color": "#ff5267"}},
increasing={"marker": {"color": "#08bdba"}},
totals={"marker": {"color": "#00b4ff"}},
)
)
fig.update_layout(title=title)
return fig
custom_charts = vm.Page(
title="Custom Charts",
components=[
vm.Graph(
id="custom_scatter",
figure=scatter_with_line(
x="sepal_length",
y="sepal_width",
hline=3.5,
data_frame=iris,
title="Custom px chart",
),
),
vm.Graph(
id="custom_waterfall",
figure=waterfall(
data_frame=waterfall_df,
measure="measure",
x="x",
y="y",
text="text",
title="Custom go chart",
),
),
],
controls=[
vm.Filter(column="petal_width", targets=["custom_scatter"]),
vm.Filter(
column="x",
targets=["custom_waterfall"],
selector=vm.Dropdown(title="Financial categories", multi=True),
),
],
)
# CUSTOM TABLE ------------------------------------------------------------------
@capture("table")
def my_custom_table(data_frame=None, chosen_columns: Optional[List[str]] = None):
"""Custom table with added logic to filter on chosen columns."""
columns = [{"name": i, "id": i} for i in chosen_columns]
defaults = {
"style_as_list_view": True,
"style_data": {"border_bottom": "1px solid var(--border-subtle-alpha-01)", "height": "40px"},
"style_header": {
"border_bottom": "1px solid var(--state-overlays-selected-hover)",
"border_top": "1px solid var(--main-container-bg-color)",
"height": "32px",
},
}
return dash_table.DataTable(data=data_frame.to_dict("records"), columns=columns, **defaults)
custom_tables = vm.Page(
title="Custom Tables",
components=[
vm.Table(
id="custom_table",
title="Custom Dash DataTable",
figure=my_custom_table(
data_frame=gapminder_2007,
chosen_columns=["country", "continent", "lifeExp", "pop", "gdpPercap"],
),
)
],
controls=[
vm.Parameter(
targets=["custom_table.chosen_columns"],
selector=vm.Dropdown(
title="Choose columns",
options=gapminder_2007.columns.to_list(),
multi=True,
),
)
],
)
# CUSTOM COMPONENTS -------------------------------------------------------------
# 1. Extend existing components
class TooltipNonCrossRangeSlider(vm.RangeSlider):
"""Custom numeric multi-selector `TooltipNonCrossRangeSlider`."""
type: Literal["other_range_slider"] = "other_range_slider"
def build(self):
"""Extend existing component by calling the super build and update properties."""
range_slider_build_obj = super().build()
range_slider_build_obj[self.id].allowCross = False
range_slider_build_obj[self.id].tooltip = {"always_visible": True, "placement": "bottom"}
return range_slider_build_obj
vm.Filter.add_type("selector", TooltipNonCrossRangeSlider)
# 2. Create new custom component
class Jumbotron(vm.VizroBaseModel):
"""New custom component `Jumbotron`."""
type: Literal["jumbotron"] = "jumbotron"
title: str
subtitle: str
text: str
def build(self):
"""Build the new component based on Dash components."""
return html.Div([html.H2(self.title), html.H3(self.subtitle), html.P(self.text)])
vm.Page.add_type("components", Jumbotron)
custom_components = vm.Page(
title="Custom Components",
components=[
Jumbotron(
title="Custom component based on new creation",
subtitle="This is a subtitle to summarize some content.",
text="This is the main body of text of the Jumbotron.",
),
vm.Graph(
id="for_custom_chart",
figure=px.scatter(
iris,
title="Iris Dataset",
x="sepal_length",
y="petal_width",
color="sepal_width",
),
),
],
controls=[
vm.Filter(
column="sepal_length",
targets=["for_custom_chart"],
selector=TooltipNonCrossRangeSlider(title="Custom component based on extension"),
)
],
)
# CUSTOM ACTIONS ---------------------------------------------------------------
@capture("action")
def my_custom_action(t: int):
"""Custom action."""
sleep(t)
custom_actions = vm.Page(
title="Custom Actions",
components=[
vm.Graph(
figure=px.scatter(
iris,
x="sepal_length",
y="petal_width",
color="species",
)
),
vm.Button(
text="Export data",
actions=[
vm.Action(function=export_data()),
vm.Action(function=my_custom_action(t=2)),
vm.Action(function=export_data(file_format="xlsx")),
],
),
],
controls=[vm.Filter(column="species", selector=vm.Dropdown(title="Species"))],
)
# DASHBOARD -------------------------------------------------------------------
components = [graphs, ag_grid, table, cards, button, containers, tabs]
controls = [filters, parameters, selectors]
actions = [export_data_action, chart_interaction]
extensions = [custom_charts, custom_tables, custom_components, custom_actions]
dashboard = vm.Dashboard(
title="Vizro Features",
pages=[home, *components, *controls, *actions, *extensions],
navigation=vm.Navigation(
nav_selector=vm.NavBar(
items=[
vm.NavLink(label="Homepage", pages=["Homepage"], icon="Home"),
vm.NavLink(
label="Features",
pages={
"Components": ["Graphs", "AG Grid", "Table", "Cards", "Button", "Containers", "Tabs"],
"Controls": ["Filters", "Parameters", "Selectors"],
"Actions": ["Export data", "Chart interaction"],
"Extensions": ["Custom Charts", "Custom Tables", "Custom Components", "Custom Actions"],
},
icon="Library Add",
),
]
)
),
)
app = Vizro().build(dashboard)
app.dash.layout.children.append(
dbc.NavLink(
["Made with ", html.Img(src=get_asset_url("images/logo.svg"), id="banner", alt="Vizro logo"), "vizro"],
href="https://github.com/mckinsey/vizro",
target="_blank",
external_link=True,
className="anchor-container",
)
)
server = app.dash.server
if __name__ == "__main__":
app.run()
|