Streamlit은 파이썬 코드만으로 웹 애플리케이션을 손쉽게 만들 수 있는 오픈소스 프레임워크이다. 머신러닝, 데이터 분석, 데이터 시각화를 진행할 때 대시보드를 빠르게 만들고 싶을 때 유용하다.
colab기준
!pip install -q streamlit
앱 실행
!streamlit run your_app.py
코랩환경에서는 오류가 난다.
해결방법은 localtunnel을 사용한다.
!npm install localtunnel
!streamlit run your_app.py &>/content/logs.txt & npx localtunnel --port 임의지정8031 & curl ipv4.icanhazip.com
코랩환경에서 실행이 된다.
%%writefile iris.py
import streamlit as st
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
# 데이터 로드
iris = sns.load_dataset('iris')
# 제목
st.title("Iris 데이터셋 시각화")
# 데이터 표시
if st.checkbox("데이터프레임 보기"):
st.write(iris)
# 종 선택
species = st.selectbox("종을 선택하세요", iris['species'].unique())
filtered_data = iris[iris['species'] == species]
# 히스토그램 변수 선택
feature = st.selectbox("시각화할 특성(Feature)을 선택하세요", iris.columns[:-1])
# 히스토그램 출력
st.subheader(f"{species}의 {feature} 분포 히스토그램")
fig, ax = plt.subplots()
sns.histplot(filtered_data[feature], kde=True, ax=ax)
st.pyplot(fig)
!streamlit run iris.py &>/content/logs.txt & npx localtunnel --port 8031 & curl ipv4.icanhazip.com
st.title(): 페이지 제목 출력
st.title("🌸 Iris 데이터셋 시각화")
웹 앱 상단에 큰 제목을 출력한다.
st.checkbox(): 체크박스 UI 컴포넌트
if st.checkbox("📄 데이터프레임 보기"):
체크 여부에 따라 조건문이 작동하며, 체크되었을 경우 데이터프레임 iris를 화면에 출력한다.
st.selectbox(): 드롭다운 메뉴 구성
species = st.selectbox("🔍 종을 선택하세요", iris['species'].unique())
사용자가 종(Species) 을 선택할 수 있는 드롭다운 메뉴를 생성한다.
데이터 필터링
filtered_data = iris[iris['species'] == species]
선택된 종(species)만 필터링한 데이터프레임을 생성한다.
두 번째 st.selectbox(): 시각화 대상 특성 선택
feature = st.selectbox("📊 시각화할 특성(Feature)을 선택하세요", iris.columns[:-1])
iris.columns[:-1]는 species를 제외한 수치형 데이터만 출력한다.
st.subheader(): 소제목 출력
st.subheader(f"{species}의 {feature} 분포 히스토그램")
사용자가 선택한 종과 특성을 기반으로 서브 타이틀을 출력한다.
| Streamlit 함수 | 설명 |
|---|---|
st.title() | 대시보드의 큰 제목을 출력 |
st.checkbox() | 체크박스를 통해 조건 설정 |
st.selectbox() | 드롭다운 메뉴를 통해 항목 선택 |
st.write() | 데이터프레임, 텍스트, 수식 등 출력 |
st.subheader() | 소제목을 출력하여 시각적 구조 제공 |
st.pyplot() | Matplotlib 그래프를 웹 앱에 시각화 |
자세한 코드는 깃허브