from pathlib import Path
from plotnine import ggplot, aes, geom_histogram, geom_vline
from faicons import icon_svg
from palmerpenguins import load_penguins
from shiny import reactive
from shiny.express import input, render, ui
= load_penguins()
df = Path(__file__).parent
app_dir
="Penguins histogram", fillable=True)
ui.page_opts(title
with ui.sidebar(title="Filter controls"):
ui.input_checkbox_group("species",
"Species",
"Adelie", "Gentoo", "Chinstrap"],
[=["Adelie", "Gentoo", "Chinstrap"],
selected
)
ui.input_checkbox_group("island",
"Island",
"Biscoe", "Dream", "Torgersen"],
[=["Biscoe", "Dream", "Torgersen"],
selected
)
with ui.layout_column_wrap(fill=False):
with ui.value_box(showcase=icon_svg("earlybirds")):
"Number of penguins"
@render.text
def count():
return filtered_df().shape[0]
with ui.value_box(showcase=icon_svg("ruler-horizontal")):
"Average bill length"
@render.text
def bill_length():
return f"{filtered_df()['bill_length_mm'].mean():.1f} mm"
with ui.value_box(showcase=icon_svg("ruler-vertical")):
"Average bill depth"
@render.text
def bill_depth():
return f"{filtered_df()['bill_depth_mm'].mean():.1f} mm"
with ui.layout_columns():
with ui.card(full_screen=True):
"Bill length")
ui.card_header(
@render.plot
def length():
return (
="bill_length_mm"))
ggplot(filtered_df(), aes(x+ geom_histogram()
+ geom_vline(
=filtered_df()["bill_length_mm"].mean(),
xintercept="green",
color="dashed",
linetype
)
)
@reactive.calc
def filtered_df():
= df[df["species"].isin(input.species())]
filt_df = filt_df[filt_df["island"].isin(input.island())]
filt_df return filt_df
1 ペンギンのヒストグラムのダッシュボードをShiny for Pythonでつくる
下記のShiny Expressのコードをapp.pyとして保存する。
下記をターミナル/コマンドプロンプトで実行するとブラウザで下図のようなダッシュボードが出てくる。
python3 -m shiny run --launch-browser app.py
2 shinyを実行ファイル化する(Mac OS)
下記のShiny Coreのコードをfile1.pyとして保存する。
from shiny import App, render, ui
from shiny._main import run_app
= ui.page_fluid(
app_ui "Hello Shiny!"),
ui.h2("n", "N", 0, 100, 20),
ui.input_slider("txt"),
ui.output_text_verbatim(
)def server(input, output, session):
@output
@render.text
def txt():
return f"n*2 is {input.n() * 2}"
= App(app_ui, server)
app =True) run_app(app,launch_browser
Macのターミナルでfile1.pyがあるフォルダにカレントディレクトリを移動してから下記を実行する
python3.13 -m venv .venv
source .venv/bin/activate
pip install pyinstaller shiny
pyinstaller -F --collect-all shiny --name file1_app2 file1.py
しばらく待つとdist/file1_app2が作成されるのでダブルクリックして実行する。すると下図の画面が出てアプリの起動が完了。
アプリの終了時はブラウザを閉じ、ターミナルでCtrl+Cを押してから閉じる。
なおShiny Expressのコードから実行ファイルをつくる方法があるのかは不明。
3 参考文献
4 Python version
import platform
"Python version "+platform.python_version()
'Python version 3.13.3'