2
4

Streamlitを使ってみる:その1

Last updated at Posted at 2023-11-17

データ解析結果をチームで共有するためのサイトを手軽に作れないか、と思い立ち、Streamlitを勉強中です。

1. 開発環境

  • MacOS Ventura
  • Anaconda

Anacondaは導入済みとする

2. 参考URL

使い方

Streamlit is an open-source Python library that makes it easy to create and share beautiful, custom web apps for machine learning and data science. In just a few minutes you can build and deploy powerful data apps. So let's get started!
Streamlitは、機械学習とデータサイエンス用の美しいカスタムWebアプリを簡単に作成して共有できるオープンソースのPythonライブラリです。わずか数分で、強力なデータアプリを構築して展開できます。それでは始めましょう!(Google翻訳)

他フレームワークとの比較

vs Shiny

3. インストール手順

streamlit用の環境を作成

% conda create -n streamlit python==3.10

streamlit環境をアクチベート

% conda activate streamlit

streamlitライブラリをインストール

% conda install -c conda-forge streamlit

streamlitのデモを起動

% streamlit hello

他に使いそうなライブラリをインストール

% conda install pandas numpy scipy scikit-learn scikit-image matplotlib seaborn jupyterlab

4. テストページを作成してみる

4-1. テキストを表示

test_st.pyファイルを作成し、下記を記述して保存

test_st.py
import streamlit as st
st.text("Hello World!")

ターミナルで実行

% streamlit run test_st.py

streamlit_test1.png

4-2. マジックコマンドでテキストを表示

test_st2.py
import streamlit as st

"Hello World!!"

streamlit_test2.png

st.textのときとフォントが違いますね。

4-3. Pandasデータフレームを表示

  • マジックコマンド
  • st.write
  • st.table

の3種類の方法で記述してみます。

test_st3.py
import streamlit as st
import pandas as pd

df = pd.DataFrame([
   {"a":1,"b":2,"c":2},
   {"a":5,"b":6,"c":4},
   {"a":2,"b":-4,"c":10}])

df #マジックコマンドで渡す

st.write(df) #st.writeで渡す

st.table(df) #st.tableで渡す

streamlit_test3.png

st.tableだけ見え方が違います。

4-4. 折れ線グラフを表示

先ほどのPandasデータフレームをラインプロットしてみる

test_st4.py
import streamlit as st
import pandas as pd

df = pd.DataFrame([
   {"a":1,"b":2,"c":2},
   {"a":5,"b":6,"c":4},
   {"a":2,"b":-4,"c":10}])

st.write(df)

st.line_chart(df)  

streamlit_test4_1.png

右上の...をクリックすると画像で保存もできます。

streamlit_test4_2.png

その2に続く。

2
4
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
2
4