|
| 1 | +import seaborn as sns |
| 2 | +from faicons import icon_svg |
| 3 | + |
| 4 | +# Import data from shared.py |
| 5 | +from shared import app_dir, df |
| 6 | + |
| 7 | +from shiny import App, reactive, render, ui |
| 8 | + |
| 9 | +app_ui = ui.page_sidebar( |
| 10 | + ui.sidebar( |
| 11 | + ui.input_slider("mass", "Mass", 2000, 6000, 6000), |
| 12 | + ui.input_checkbox_group( |
| 13 | + "species", |
| 14 | + "Species", |
| 15 | + ["Adelie", "Gentoo", "Chinstrap"], |
| 16 | + selected=["Adelie", "Gentoo", "Chinstrap"], |
| 17 | + ), |
| 18 | + title="Filter controls", |
| 19 | + ), |
| 20 | + ui.layout_column_wrap( |
| 21 | + ui.value_box( |
| 22 | + "Number of penguins", |
| 23 | + ui.output_text("count"), |
| 24 | + showcase=icon_svg("earlybirds"), |
| 25 | + ), |
| 26 | + ui.value_box( |
| 27 | + "Average bill length", |
| 28 | + ui.output_text("bill_length"), |
| 29 | + showcase=icon_svg("ruler-horizontal"), |
| 30 | + ), |
| 31 | + ui.value_box( |
| 32 | + "Average bill depth", |
| 33 | + ui.output_text("bill_depth"), |
| 34 | + showcase=icon_svg("ruler-vertical"), |
| 35 | + ), |
| 36 | + fill=False, |
| 37 | + ), |
| 38 | + ui.layout_columns( |
| 39 | + ui.card( |
| 40 | + ui.card_header("Bill length and depth"), |
| 41 | + ui.output_plot("length_depth"), |
| 42 | + full_screen=True, |
| 43 | + ), |
| 44 | + ui.card( |
| 45 | + ui.card_header("Penguin data"), |
| 46 | + ui.output_data_frame("summary_statistics"), |
| 47 | + full_screen=True, |
| 48 | + ), |
| 49 | + ), |
| 50 | + ui.include_css(app_dir / "styles.css"), |
| 51 | + title="Penguins dashboard", |
| 52 | + fillable=True, |
| 53 | +) |
| 54 | + |
| 55 | + |
| 56 | +def server(input, output, session): |
| 57 | + @reactive.calc |
| 58 | + def filtered_df(): |
| 59 | + filt_df = df[df["species"].isin(input.species())] |
| 60 | + filt_df = filt_df.loc[filt_df["body_mass_g"] < input.mass()] |
| 61 | + return filt_df |
| 62 | + |
| 63 | + @render.text |
| 64 | + def count(): |
| 65 | + return filtered_df().shape[0] |
| 66 | + |
| 67 | + @render.text |
| 68 | + def bill_length(): |
| 69 | + return f"{filtered_df()['bill_length_mm'].mean():.1f} mm" |
| 70 | + |
| 71 | + @render.text |
| 72 | + def bill_depth(): |
| 73 | + return f"{filtered_df()['bill_depth_mm'].mean():.1f} mm" |
| 74 | + |
| 75 | + @render.plot |
| 76 | + def length_depth(): |
| 77 | + return sns.scatterplot( |
| 78 | + data=filtered_df(), |
| 79 | + x="bill_length_mm", |
| 80 | + y="bill_depth_mm", |
| 81 | + hue="species", |
| 82 | + ) |
| 83 | + |
| 84 | + @render.data_frame |
| 85 | + def summary_statistics(): |
| 86 | + cols = [ |
| 87 | + "species", |
| 88 | + "island", |
| 89 | + "bill_length_mm", |
| 90 | + "bill_depth_mm", |
| 91 | + "body_mass_g", |
| 92 | + ] |
| 93 | + return render.DataGrid(filtered_df()[cols], filters=True) |
| 94 | + |
| 95 | + |
| 96 | +app = App(app_ui, server) |
0 commit comments