728x90
반응형
이전 내용
[파이썬] Streamlit으로 웹 페이지 만들기 - 2
이전 내용 [파이썬] Streamlit 으로 웹페이지 만들기 - 1Streamlit Streamlit은 Python으로 빠르고 간편하게 웹 애플리케이션을 만들 수 있는 도구이다. 간단한 기능을 가진 데이터 웹 어플리케이션을, 빠
puppy-foot-it.tistory.com
시각화
이번엔 Streamlit의 시각화 기능을 이용해 보려 한다. Streamlit 공식 페이지에 접속하면, 해당 라이브러리 사용과 관련된 자세한 설명과 내용이 담겨 있다. 그 중 튜토리얼에 있는 하단의 그래프를 띄워보려 한다.
https://docs.streamlit.io/develop/tutorials/elements/dataframe-row-selections
▶ 두 개의 탭을 생성하여 차트를 그릴 수 있다.
★ 필요한 라이브러리를 import 할 때 Faker 가 없을 수도 있기 때문에,
import numpy as np
import pandas as pd
import streamlit as st
from faker import Faker
Faker를 설치한다.
* Faker: 가짜 데이터를 생성하는 도구
pip install faker
◆ 전체 코드
: Streamlit 공식 사이트에 올라와 있다.
import numpy as np
import pandas as pd
import streamlit as st
from faker import Faker
@st.cache_data
def get_profile_dataset(number_of_items: int = 20, seed: int = 0) -> pd.DataFrame:
new_data = []
fake = Faker()
np.random.seed(seed)
Faker.seed(seed)
for i in range(number_of_items):
profile = fake.profile()
new_data.append(
{
"name": profile["name"],
"daily_activity": np.random.rand(25),
"activity": np.random.randint(2, 90, size=12),
}
)
profile_df = pd.DataFrame(new_data)
return profile_df
column_configuration = {
"name": st.column_config.TextColumn(
"Name", help="The name of the user", max_chars=100, width="medium"
),
"activity": st.column_config.LineChartColumn(
"Activity (1 year)",
help="The user's activity over the last 1 year",
width="large",
y_min=0,
y_max=100,
),
"daily_activity": st.column_config.BarChartColumn(
"Activity (daily)",
help="The user's activity in the last 25 days",
width="medium",
y_min=0,
y_max=1,
),
}
select, compare = st.tabs(["Select members", "Compare selected"])
with select:
st.header("All members")
df = get_profile_dataset()
event = st.dataframe(
df,
column_config=column_configuration,
use_container_width=True,
hide_index=True,
on_select="rerun",
selection_mode="multi-row",
)
st.header("Selected members")
people = event.selection.rows
filtered_df = df.iloc[people]
st.dataframe(
filtered_df,
column_config=column_configuration,
use_container_width=True,
)
with compare:
activity_df = {}
for person in people:
activity_df[df.iloc[person]["name"]] = df.iloc[person]["activity"]
activity_df = pd.DataFrame(activity_df)
daily_activity_df = {}
for person in people:
daily_activity_df[df.iloc[person]["name"]] = df.iloc[person]["daily_activity"]
daily_activity_df = pd.DataFrame(daily_activity_df)
if len(people) > 0:
st.header("Daily activity comparison")
st.bar_chart(daily_activity_df)
st.header("Yearly activity comparison")
st.line_chart(activity_df)
else:
st.markdown("No members selected.")
- @st.cache_data 데코레이터: 함수의 결과를 캐시. 향후 호출 시 성능을 향상시킴.
- def get_profile_dataset: 사용자 프로필 데이터를 생성하는 함수. Faker를 사용해 가상의 사용자 프로필을 만들고, 각 프로필에 대해 랜덤한 활동 데이터를 생성 (-> pd.DataFrame: 결과를 데이터프레임 형식으로 반환)
- column_configuration: 데이터프레임의 각 열에 대한 설정 정의 (각 열의 설명, 최대 문자 수, 너비, 최소/최대 값 등 설정)
- select, compare = st.tabs(["Select members", "Compare selected"]): 탭 기능을 사용하여 두 개의 탭 생성
- 탭1. with select: 전체 사용자 프로필 탭 (st.dataframe()을 사용하여 데이터프레임을 표시하고, 선택된 행의 정보를 가져와 filtered_df 에 대한 새로운 데이터프레임을 생성하여 표시)
- 탭2. with compare: 선택된 사용자의 활동 정보 비교 탭 (일일 및 연간 활동 데이터 저장하여 일일 활동은 Bar Chart로, 연간 활동은 Line Chart로 표시). 사용자 미선택 시에는 "No members selected." 표시
728x90
반응형
'[파이썬 Projects] > <파이썬 웹개발>' 카테고리의 다른 글
[파이썬] Streamlit 웹 개발 - 5: 로또 번호 생성 페이지 (0) | 2025.03.18 |
---|---|
[파이썬] Streamlit 웹 개발 - 4: 차트 (1) | 2025.03.18 |
[파이썬] Streamlit 웹 개발 - 2: DataFrame (0) | 2025.03.18 |
[파이썬] Streamlit 웹 개발 - 1: 기초 (0) | 2025.03.18 |
[파이썬] FastAPI - FastAPI와 Jinja2 고급 문법 (0) | 2024.08.22 |