|
| 1 | +from pathlib import Path |
| 2 | + |
| 3 | +import pandas as pd |
| 4 | +import seaborn as sns |
| 5 | + |
| 6 | +from shiny import reactive |
| 7 | +from shiny.express import input, render, ui |
| 8 | + |
| 9 | +sns.set_theme(style="white") |
| 10 | +df = pd.read_csv(Path(__file__).parent / "penguins.csv", na_values="NA") |
| 11 | +species = ["Adelie", "Gentoo", "Chinstrap"] |
| 12 | + |
| 13 | +ui.page_opts(fillable=True) |
| 14 | + |
| 15 | + |
| 16 | +def count_species(df, species): |
| 17 | + return df[df["Species"] == species].shape[0] |
| 18 | + |
| 19 | + |
| 20 | +with ui.sidebar(): |
| 21 | + ui.input_slider("mass", "Mass", 2000, 6000, 3400) |
| 22 | + ui.input_checkbox_group("species", "Filter by species", species, selected=species) |
| 23 | + |
| 24 | + |
| 25 | +@reactive.Calc |
| 26 | +def filtered_df() -> pd.DataFrame: |
| 27 | + filt_df = df[df["Species"].isin(input.species())] |
| 28 | + filt_df = filt_df.loc[filt_df["Body Mass (g)"] > input.mass()] |
| 29 | + return filt_df |
| 30 | + |
| 31 | + |
| 32 | +with ui.layout_columns(): |
| 33 | + with ui.value_box(theme="primary"): |
| 34 | + "Adelie" |
| 35 | + |
| 36 | + @render.text |
| 37 | + def adelie_count(): |
| 38 | + return count_species(filtered_df(), "Adelie") |
| 39 | + |
| 40 | + with ui.value_box(theme="primary"): |
| 41 | + "Gentoo" |
| 42 | + |
| 43 | + @render.text |
| 44 | + def gentoo_count(): |
| 45 | + return count_species(filtered_df(), "Gentoo") |
| 46 | + |
| 47 | + with ui.value_box(theme="primary"): |
| 48 | + "Chinstrap" |
| 49 | + |
| 50 | + @render.text |
| 51 | + def chinstrap_count(): |
| 52 | + return count_species(filtered_df(), "Chinstrap") |
| 53 | + |
| 54 | + |
| 55 | +with ui.layout_columns(): |
| 56 | + with ui.card(): |
| 57 | + ui.card_header("Summary statistics") |
| 58 | + |
| 59 | + @render.data_frame |
| 60 | + def summary_statistics(): |
| 61 | + display_df = filtered_df()[ |
| 62 | + [ |
| 63 | + "Species", |
| 64 | + "Island", |
| 65 | + "Bill Length (mm)", |
| 66 | + "Bill Depth (mm)", |
| 67 | + "Body Mass (g)", |
| 68 | + ] |
| 69 | + ] |
| 70 | + return render.DataGrid(display_df, filters=True) |
| 71 | + |
| 72 | + with ui.card(): |
| 73 | + ui.card_header("Penguin bills") |
| 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 | + ) |
0 commit comments