728x90
반응형
안녕하세요. 이번에는 코드별로 따로 설명을 하지 않고, 전체코드에 주석으로 설명을 대체하였습니다.
전체 코드& 해석
import streamlit as st
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
def main():
with st.sidebar:
st.header("sidebar")
day = st.selectbox("select a day", ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
#사이드 바를 만들고, 사이드바 헤더를 'sidebar'로 지정한다.
#day에 셀렉트박스를 만들어서 요일을 넣어준다.
tips = sns.load_dataset("tips")
filtered_tips = tips[tips["day"] == day]
top_bill = filtered_tips["total_bill"].max()
top_tip = filtered_tips["tip"].max()
# sns로 데이터셋을 불러온다.
#불러온 데이터를 day로 필터해준다. -> 위에 만든 day 셀렉트박스를 변경하면 값이 바뀌게 하기 위함
#top_bill, top_tip의 max값을 보여주게 정의한다.
tab1,tab2,tab3 = st.sidebar.tabs(["Total Bill","Tip","Size"])
#sidebar에 tabs을 만들어서 각각 totalbill,tip,size를 넣어준다.
#아래는 각각의 탭을 선택하면 차트가 보이게끔 시각화한 코드이다.
#totalbill과 tip은 int형 자료로 histplot으로 시각화했다.
#size는 boxplot으로 성별(sex)에 따른 tip을 시각화했다.
with tab1: #total bill
fig, ax = plt.subplots()
st.header("Total Bill Amounts")
sns.histplot(filtered_tips["total_bill"],kde=False,ax=ax)
st.pyplot(fig)
with tab2: #tip
fig, ax = plt.subplots()
st.header("Tip Amounts")
sns.histplot(filtered_tips["tip"],kde=False,ax=ax)
st.pyplot(fig)
with tab3: #size
fig, ax = plt.subplots()
st.header("Table Sizes")
sns.boxplot(data=filtered_tips,x="sex",y="tip",ax=ax)
st.pyplot(fig)
col1, col2, col3 = st.columns([1,1,1]) #div태그 추가
#columns는 tab과 비슷한데 []안에는 영역의 크기를 의미한다. [1,2,1]로 변경하면 가운데 col2의 범위가 2로 커진다.
#컬럼안에 metric(1,2) << , 로 컬럼위치를 정할 수 있다.
with col1:
st.metric("Top Bill", f"${top_bill:.2f}")
with col2:
st.metric("Top Tip", f"${top_tip:.2f}")
with col3:
st.metric("Tip Rate", f"{top_tip/top_bill*100:.2f}%","팁 비중")
if __name__ == "__main__":
main()
실행 결과
- 아래 이미지와 같이 [셀렉트박스]에 요일이 들어가 있고, 요일을 클릭하면 해당 요일의 정보가 보여집니다.
- tabs로 만든 [total bill, tip, size] plot들도 잘 보여지는 모습입니다.
**공식 문서 참조
- columns
- tabs
728x90
반응형
'programming > Python' 카테고리의 다른 글
[파이썬/머신러닝] SVM모델로 다항 분류 모델링 (0) | 2024.02.04 |
---|---|
[파이썬] st.text_input으로 텍스트 입력하기 (0) | 2023.12.29 |
[파이썬] streamlit의 slider 이용해서 위젯 만들기 (0) | 2023.12.28 |
[파이썬] streamlit의 plotly_chart로 그룹별로 차트 시각화하기 (0) | 2023.12.28 |
[파이썬] streamlit의 metric활용하기(전일대비 등락폭 등 시각화) (0) | 2023.12.27 |