cpsievert commited on
Commit
5d0f41e
1 Parent(s): 5bf99de

Migrate to dashboard-tips example

Browse files
Files changed (1) hide show
  1. app.py +150 -139
app.py CHANGED
@@ -1,151 +1,162 @@
1
- from pathlib import Path
2
- from typing import List, Dict, Tuple
3
- import matplotlib.colors as mpl_colors
4
-
5
- import pandas as pd
6
- import seaborn as sns
7
- import shinyswatch
8
-
9
- from shiny import App, Inputs, Outputs, Session, reactive, render, req, ui
10
-
11
- sns.set_theme()
12
-
13
- www_dir = Path(__file__).parent.resolve() / "www"
14
-
15
- df = pd.read_csv(Path(__file__).parent / "penguins.csv", na_values="NA")
16
- numeric_cols: List[str] = df.select_dtypes(include=["float64"]).columns.tolist()
17
- species: List[str] = df["Species"].unique().tolist()
18
- species.sort()
19
-
20
- app_ui = ui.page_fillable(
21
- shinyswatch.theme.minty(),
22
- ui.layout_sidebar(
23
- ui.sidebar(
24
- # Artwork by @allison_horst
25
- ui.input_selectize(
26
- "xvar",
27
- "X variable",
28
- numeric_cols,
29
- selected="Bill Length (mm)",
30
- ),
31
- ui.input_selectize(
32
- "yvar",
33
- "Y variable",
34
- numeric_cols,
35
- selected="Bill Depth (mm)",
36
- ),
37
- ui.input_checkbox_group(
38
- "species", "Filter by species", species, selected=species
39
- ),
40
- ui.hr(),
41
- ui.input_switch("by_species", "Show species", value=True),
42
- ui.input_switch("show_margins", "Show marginal plots", value=True),
43
- ),
44
- ui.output_ui("value_boxes"),
45
- ui.output_plot("scatter", fill=True),
46
- ui.help_text(
47
- "Artwork by ",
48
- ui.a("@allison_horst", href="https://twitter.com/allison_horst"),
49
- class_="text-end",
50
- ),
51
- ),
52
- )
53
-
54
-
55
- def server(input: Inputs, output: Outputs, session: Session):
56
- @reactive.Calc
57
- def filtered_df() -> pd.DataFrame:
58
- """Returns a Pandas data frame that includes only the desired rows"""
59
-
60
- # This calculation "req"uires that at least one species is selected
61
- req(len(input.species()) > 0)
62
-
63
- # Filter the rows so we only include the desired species
64
- return df[df["Species"].isin(input.species())]
65
-
66
- @output
67
- @render.plot
68
- def scatter():
69
- """Generates a plot for Shiny to display to the user"""
70
-
71
- # The plotting function to use depends on whether margins are desired
72
- plotfunc = sns.jointplot if input.show_margins() else sns.scatterplot
73
-
74
- plotfunc(
75
- data=filtered_df(),
76
- x=input.xvar(),
77
- y=input.yvar(),
78
- palette=palette,
79
- hue="Species" if input.by_species() else None,
80
- hue_order=species,
81
- legend=False,
82
- )
83
-
84
- @output
85
- @render.ui
86
- def value_boxes():
87
- df = filtered_df()
88
-
89
- def penguin_value_box(title: str, count: int, bgcol: str, showcase_img: str):
90
- return ui.value_box(
91
- title,
92
- count,
93
- {"class_": "pt-1 pb-0"},
94
- showcase=ui.fill.as_fill_item(
95
- ui.tags.img(
96
- {"style": "object-fit:contain;"},
97
- src=showcase_img,
98
- )
99
- ),
100
- theme_color=None,
101
- style=f"background-color: {bgcol};",
102
  )
103
 
104
- if not input.by_species():
105
- return penguin_value_box(
106
- "Penguins",
107
- len(df.index),
108
- bg_palette["default"],
109
- # Artwork by @allison_horst
110
- showcase_img="penguins.png",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  )
112
 
113
- value_boxes = [
114
- penguin_value_box(
115
- name,
116
- len(df[df["Species"] == name]),
117
- bg_palette[name],
118
- # Artwork by @allison_horst
119
- showcase_img=f"{name}.png",
120
  )
121
- for name in species
122
- # Only include boxes for _selected_ species
123
- if name in input.species()
124
- ]
125
 
126
- return ui.layout_column_wrap(*value_boxes, width = 1 / len(value_boxes))
127
 
128
 
129
- # "darkorange", "purple", "cyan4"
130
- colors = [[255, 140, 0], [160, 32, 240], [0, 139, 139]]
131
- colors = [(r / 255.0, g / 255.0, b / 255.0) for r, g, b in colors]
 
 
132
 
133
- palette: Dict[str, Tuple[float, float, float]] = {
134
- "Adelie": colors[0],
135
- "Chinstrap": colors[1],
136
- "Gentoo": colors[2],
137
- "default": sns.color_palette()[0], # type: ignore
138
- }
139
 
140
- bg_palette = {}
141
- # Use `sns.set_style("whitegrid")` to help find approx alpha value
142
- for name, col in palette.items():
143
- # Adjusted n_colors until `axe` accessibility did not complain about color contrast
144
- bg_palette[name] = mpl_colors.to_hex(sns.light_palette(col, n_colors=7)[1]) # type: ignore
 
145
 
146
 
147
- app = App(
148
- app_ui,
149
- server,
150
- static_assets=str(www_dir),
151
- )
 
1
+ import faicons as fa
2
+ import plotly.express as px
3
+
4
+ # Load data and compute static values
5
+ from shared import app_dir, tips
6
+ from shinywidgets import render_plotly
7
+
8
+ from shiny import reactive, render
9
+ from shiny.express import input, ui
10
+
11
+ bill_rng = (min(tips.total_bill), max(tips.total_bill))
12
+
13
+ # Add page title and sidebar
14
+ ui.page_opts(title="Restaurant tipping", fillable=True)
15
+
16
+ with ui.sidebar(open="desktop"):
17
+ ui.input_slider(
18
+ "total_bill",
19
+ "Bill amount",
20
+ min=bill_rng[0],
21
+ max=bill_rng[1],
22
+ value=bill_rng,
23
+ pre="$",
24
+ )
25
+ ui.input_checkbox_group(
26
+ "time",
27
+ "Food service",
28
+ ["Lunch", "Dinner"],
29
+ selected=["Lunch", "Dinner"],
30
+ inline=True,
31
+ )
32
+ ui.input_action_button("reset", "Reset filter")
33
+
34
+ # Add main content
35
+ ICONS = {
36
+ "user": fa.icon_svg("user", "regular"),
37
+ "wallet": fa.icon_svg("wallet"),
38
+ "currency-dollar": fa.icon_svg("dollar-sign"),
39
+ "ellipsis": fa.icon_svg("ellipsis"),
40
+ }
41
+
42
+ with ui.layout_columns(fill=False):
43
+ with ui.value_box(showcase=ICONS["user"]):
44
+ "Total tippers"
45
+
46
+ @render.express
47
+ def total_tippers():
48
+ tips_data().shape[0]
49
+
50
+ with ui.value_box(showcase=ICONS["wallet"]):
51
+ "Average tip"
52
+
53
+ @render.express
54
+ def average_tip():
55
+ d = tips_data()
56
+ if d.shape[0] > 0:
57
+ perc = d.tip / d.total_bill
58
+ f"{perc.mean():.1%}"
59
+
60
+ with ui.value_box(showcase=ICONS["currency-dollar"]):
61
+ "Average bill"
62
+
63
+ @render.express
64
+ def average_bill():
65
+ d = tips_data()
66
+ if d.shape[0] > 0:
67
+ bill = d.total_bill.mean()
68
+ f"${bill:.2f}"
69
+
70
+
71
+ with ui.layout_columns(col_widths=[6, 6, 12]):
72
+ with ui.card(full_screen=True):
73
+ ui.card_header("Tips data")
74
+
75
+ @render.data_frame
76
+ def table():
77
+ return render.DataGrid(tips_data())
78
+
79
+ with ui.card(full_screen=True):
80
+ with ui.card_header(class_="d-flex justify-content-between align-items-center"):
81
+ "Total bill vs tip"
82
+ with ui.popover(title="Add a color variable", placement="top"):
83
+ ICONS["ellipsis"]
84
+ ui.input_radio_buttons(
85
+ "scatter_color",
86
+ None,
87
+ ["none", "sex", "smoker", "day", "time"],
88
+ inline=True,
89
+ )
90
+
91
+ @render_plotly
92
+ def scatterplot():
93
+ color = input.scatter_color()
94
+ return px.scatter(
95
+ tips_data(),
96
+ x="total_bill",
97
+ y="tip",
98
+ color=None if color == "none" else color,
99
+ trendline="lowess",
 
 
100
  )
101
 
102
+ with ui.card(full_screen=True):
103
+ with ui.card_header(class_="d-flex justify-content-between align-items-center"):
104
+ "Tip percentages"
105
+ with ui.popover(title="Add a color variable"):
106
+ ICONS["ellipsis"]
107
+ ui.input_radio_buttons(
108
+ "tip_perc_y",
109
+ "Split by:",
110
+ ["sex", "smoker", "day", "time"],
111
+ selected="day",
112
+ inline=True,
113
+ )
114
+
115
+ @render_plotly
116
+ def tip_perc():
117
+ from ridgeplot import ridgeplot
118
+
119
+ dat = tips_data()
120
+ dat["percent"] = dat.tip / dat.total_bill
121
+ yvar = input.tip_perc_y()
122
+ uvals = dat[yvar].unique()
123
+
124
+ samples = [[dat.percent[dat[yvar] == val]] for val in uvals]
125
+
126
+ plt = ridgeplot(
127
+ samples=samples,
128
+ labels=uvals,
129
+ bandwidth=0.01,
130
+ colorscale="viridis",
131
+ colormode="row-index",
132
  )
133
 
134
+ plt.update_layout(
135
+ legend=dict(
136
+ orientation="h", yanchor="bottom", y=1.02, xanchor="center", x=0.5
137
+ )
 
 
 
138
  )
 
 
 
 
139
 
140
+ return plt
141
 
142
 
143
+ ui.include_css(app_dir / "styles.css")
144
+
145
+ # --------------------------------------------------------
146
+ # Reactive calculations and effects
147
+ # --------------------------------------------------------
148
 
 
 
 
 
 
 
149
 
150
+ @reactive.calc
151
+ def tips_data():
152
+ bill = input.total_bill()
153
+ idx1 = tips.total_bill.between(bill[0], bill[1])
154
+ idx2 = tips.time.isin(input.time())
155
+ return tips[idx1 & idx2]
156
 
157
 
158
+ @reactive.effect
159
+ @reactive.event(input.reset)
160
+ def _():
161
+ ui.update_slider("total_bill", value=bill_rng)
162
+ ui.update_checkbox_group("time", selected=["Lunch", "Dinner"])