LoginSignup
22
16

【15分で出来る】Streamlit爆速入門

Posted at

はじめに

StreamlitはPythonだけでWebアプリを作ることのできるフレームワークです。
類似のフレームワークはいくつかありますが、その中で最も簡単だと思います。

この記事はStreamlitをこれから使い始める方に向けた、15分で出来る爆速入門チュートリアルです。

1. 導入
2. コンポーネントチートシート
3. 作ってみる(Web上で試せるPlaygroundあり)

導入

  • インストール
pip install streamlit
  • サンプルアプリ作成
app.py
import streamlit as st

st.write("hello streamlit")
  • 実行
streamlit run app.py

IMG_9891.jpeg

コンポーネントチートシート

公式のチートシートから、私がよく使うものを抜粋して以下のカテゴリに分けて整理しました。

  • テキストや画像、データなど情報を表示するもの
  • ユーザーからの入力を受け取るもの
  • ページのレイアウトを調整するもの
  • 処理を制御するもの

※codepen上でチャート関連のAPIがエラーになってしまうので除いています。

See the Pen Store by ppspps824 (@ppspps824) on CodePen.

表示系

# テキスト(マークダウンで書けます。)
st.write("# title")

# 注釈
st.caption("注釈")

# 画像
st.image("https://ul.h3z.jp/tbfgZLSX.webp")

# テーブル
import pandas as pd
df = pd.DataFrame(
        {
            "first column": [1, 2, 3, 4],
            "second column": [10, 20, 30, 40],
        }
    )
st.write(df)

# チャート
st.line_chart(df)

# その他にもmatplotlib,altair,vega_lite,plotly,bokeh,,graphvizあたりを利用するAPIがあります。

ユーザー入力系

# テキスト入力
name = st.text_input("名前")

# 数値入力
age = st.number_input("年齢",step=1)

st.write(f"名前: {name}")
st.write(f"年齢: {age}")

## ボタン
if st.button("Push"):
    st.write("ボタンを押しました")

# プルダウン
select = st.selectbox("好きな果物",options=["りんご","ばなな","いちご"])
st.write(select)

# プルダウン(複数選択)
multi_select = st.multiselect("好きな色",options=["","",""])
st.write(multi_select)

# チェックボックス
check = st.checkbox("OK")
st.write(f"チェック:{check}")

# ラジオボタン
radio = st.radio("選択", ["", ""])
st.write(f"ラジオ:{radio}")

# ファイルアップロード
uploaded_file=st.file_uploader("Upload",type=["csv"])
if uploaded_file:
    dataframe = pd.read_csv(uploaded_file)
    st.write(dataframe)

レイアウト系

# ワイドレイアウト
st.set_page_config(layout="wide")

# 横に並べる
cols = st.columns(2)
with cols[0]:
    st.write("列1")
with cols[1]:
    st.write("列2")

# タブ
tabs = st.tabs(["タブ1","タブ2"])
with tabs[0]:
    st.write("タブ1")
with tabs[1]:
    st.write("タブ2")
    
# アコーディオン
with st.expander("開きます"):
    st.write("開きました")

# サイドバー
with st.sidebar:
    st.write("サイドバー内に表示されます")

処理系

# 状態管理
st.session_state.name = "aaa" # 再処理が行われてもクリアされない

# 再処理
st.rerun()

# 処理停止
st.stop()

作ってみる

以下の題材から一つ選んで作ってみましょう。

  • 苗字と名前を入力するとフルネームを入れて挨拶してくれるアプリ
  • CSVをアップロードするとテーブルで表示してくれるアプリ
  • BMI計算アプリ ※BMI = 体重kg ÷ 身長mの二乗

※Web上で試せるPlayground(読み込みに少し時間がかかります。)

See the Pen Store by ppspps824 (@ppspps824) on CodePen.

あるいはこちら

おわりに

入門完了です!お疲れ様でした。

st.balloons()

公式ドキュメントが非常に見やすいので詳細はこちらをご覧ください。

22
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
16