LoginSignup
211
229

More than 3 years have passed since last update.

Streamlit を用いたデータ分析アプリ制作

Last updated at Posted at 2020-10-16

Streamlit とは

本稿では、Streamlit の使い方を説明する。
Streamlit とは、フロントエンドアプリケーションを作成できる python のフレームワークである。Pandas の DataFrame や、 plotly・altair といった描画ライブラリで作成したグラフを埋め込むことができ、工夫次第でデータ分析にも応用することができる。

環境

  • macOS Catalina (ver.10.15.6)

インストール

いくつかの方法でインストールすることできる。
1) pip でインストールする。公式HP推奨

ターミナル
pip install streamlit

2) conda で仮想環境を構築する。公式Forum参照

ターミナル
conda create -y -n streamlit python=3.7
conda activate streamlit
pip install streamlit

ファイルの実行

Python ファイルを以下のように実行する。

ターミナル
streamlit run ファイル名.py

Streamlit の機能

公式 HP の API reference に、streamlit の機能がまとめられている。その中でデータ分析に活用できる機能を中心にまとめた。

タイトルの表示

st_app.py
import streamlit as st
st.title('My app')

スクリーンショット 2020-10-16 23.51.02.png

文書の表示

st_app.py
import streamlit as st
st.write("Good morning")

スクリーンショット 2020-10-16 23.51.14.png

DataFrame の表示

st_app.py
import streamlit as st
import pandas as pd
st.table(pd.DataFrame({
    'first column': [1, 2, 3, 4],
    'second column': [10, 20, 30, 40]
}))

スクリーンショット 2020-10-16 23.51.22.png

Markdown の表示

st_app.py
import streamlit as st
st.markdown('# Markdown documents')

Plotly の表示

Plotlyは、python 描画ライブラリのひとつで、様々な種類のグラフを作成できる。

st_app.py
import streamlit as st
import plotly.graph_objs as go

animals = ['giraffes', 'orangutans', 'monkeys']
populations = [20, 14, 23]

fig = go.Figure(data=[go.Bar(x=animals, y=populations)])

fig.update_layout(
    xaxis = dict(
        tickangle = 0,
        title_text = "Animal",
        title_font = {"size": 20},
        title_standoff = 25),
    yaxis = dict(
        title_text = "Populations",
        title_standoff = 25),
    title ='Title')

st.plotly_chart(fig, use_container_width=True)

スクリーンショット 2020-10-16 22.42.45.png

Altair の表示

Altair は、python 描画ライブラリのひとつで、様々な種類のグラフを作成できる。Pandas の DataFrame でデータを入力するのが特徴である。【Python】グラフ作成ライブラリ Altair の使い方

st_app.py
import streamlit as st
import altair as alt
from vega_datasets import data

source = data.cars()

fig = alt.Chart(source).mark_circle(size=60).encode(
    x='Horsepower',
    y='Miles_per_Gallon',
    color='Origin',
    tooltip=['Name', 'Origin', 'Horsepower', 'Miles_per_Gallon']
).properties(
    width=500,
    height=500
).interactive()

st.write(fig)

スクリーンショット 2020-10-16 22.56.31.png

ボタンの表示

Altair は bool 型を返すボタンを表示させることができる。

st_app.py
import streamlit as st
answer = st.button('Say hello')

if answer == True:
     st.write('Why hello there')
else:
     st.write('Goodbye')

【押す前】
スクリーンショット 2020-10-19 10.00.35.png

【押した後】
スクリーンショット 2020-10-19 10.03.34.png

チェックボタンの表示

bool 型を返すチェックボタンの表示も可能である。

st_app.py
import streamlit as st
agree = st.checkbox('I agree')

if agree == True :
     st.write('Great!')

【チェックなし】
スクリーンショット 2020-10-19 10.09.26.png

【チェックあり】
スクリーンショット 2020-10-19 10.11.17.png

ラジオボタンの表示

ラジオボタンで要素を選択することも可能である。

st_app.py
import streamlit as st
genre = st.radio(
     "What's your favorite movie genre",
     ('Comedy', 'Drama', 'Documentary'))

if genre == 'Comedy':
     st.write('You selected comedy.')
else:
     st.write("You didn't select comedy.")

スクリーンショット 2020-10-19 10.15.51.png

ドロップダウンの表示

ドロップダウンから1つだけ選択する場合は以下のとおり。

st_app.py
import streamlit as st
option = st.selectbox(
    'How would you like to be contacted?',
     ('Email', 'Home phone', 'Mobile phone'))
st.write('You selected:', option)

スクリーンショット 2020-10-16 23.46.55.png

ドロップダウンから2つ以上同時に選択する場合は以下のとおり。デフォルトで Yellow, Redの2つが選択されている。

st_app.py
import streamlit as st
options = st.multiselect(
    'What are your favorite colors',
    ['Green', 'Yellow', 'Red', 'Blue'],
    ['Yellow', 'Red'])

st.table(options)

スクリーンショット 2020-10-16 23.47.16.png

スライダーの表示

1 つの値を選択する場合は以下のとおり。
以下の例では、最小値0、最大値130、間隔1、初期値25 で動くスライダーを表示させる。

st_app.py
import streamlit as st
age = st.slider('How old are you?',  min_value=0, max_value=130, step=1, value=25)
st.write("I'm ", age, 'years old')

スクリーンショット 2020-10-16 23.14.24.png

2 つの値を選択する場合は以下のとおり。
以下の例では、最小値0.0、最大値100.0、初期値(25.0,75.0)で動くスライダーを表示させる。

st_app.py
import streamlit as st
values = st.slider(
    'Select a range of values',
   0.0, 100.0, (25.0, 75.0))
st.write('Values:', values)

スクリーンショット 2020-10-16 23.14.34.png

応用例

211
229
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
211
229