ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [5월 1주차-5/8]🎈 Python으로 웹 대시보드 만들기- Streamlit
    Why Not SW CAMP 5기/수업 기록 2025. 5. 8. 15:16

     

    데이터 분석하거나 시각화해서 보여줄 일이 많은데, 매번 노트북만으론 부족하다고 느껴본 적 있지 않나요?
    그럴 땐 Streamlit을 사용해보세요. 딱 몇 줄의 Python 코드만으로 웹 대시보드를 만들 수 있습니다.


    🌟 Streamlit이란?

    Streamlit은 Python으로 웹 앱을 만들 수 있는 오픈소스 프레임워크입니다.
    특히 데이터 분석가나 머신러닝 개발자가 빠르게 결과를 공유하거나 인터랙티브하게 만들고 싶을 때 유용하죠.

    설치도 간단합니다.

    pip install streamlit
    

    🧪 오늘 배운 내용 요약

    📌 기본 구성 요소 출력

    
    df = pd.read_csv('./datasets/CO2_emissions/CO2_Emissions.csv')
    st.dataframe(df)
    
    st.title('Title')
    st.header('header')
    st.subheader('subheader')
    
    st.markdown(
        '''
        **markdown**\\
        이루비 보고싶어요 흑흑흑 루비야 사랑해 ㅜㅜㅜㅜ
        :red[Red] **Bold** *Italic*
        '''
    )
    
    st.text(
        '''
        text
        냐냐야냐냔ㅇㄴ  냥냥냐냐냔ㅇ?
        '''
    )


    📌 버튼과 토글

    st.button(), st.checkbox(), st.toggle()
    
    • 버튼 클릭 시 특정 함수 실행
    • 토글로 상태 제어
    st.divider()
    st.subheader('Button')
    
    def button_write():
        st.write('button activated')
    
    st.button('Reset', type='primary')
    st.button('activate', on_click=button_write)
    
    st.button('Reset2', type='primary')
    if st.button('activate2'):
        st.write('button activated2')
    
    st.divider()
    st.subheader('Checkbox & Toggle')
    
    active = st.checkbox('I agree.')
    if active:
        st.text('Great!')
    
    toggle = st.toggle('Turn on the switch!', value=True)
    
    if toggle:
        st.text('Switch is turned on!')
    else:
        st.text('Switch is turned off!')


    📌 셀렉트/라디오 입력 받기

    st.divider()
    st.subheader('Selectbox & Radio & Multiselect')
    option1 = st.selectbox(
        label='your selection is',
        options=['Car', 'Airplane', 'Train', 'Ship'],
        index=None,
        placeholder='select transportation'
    )
    st.text('you selected: {}'.format(option1))
    
    option2 = st.radio(
        'What is your favorite movie genre',
        ['Comedy', 'Drama', 'Documentary'],
        captions=['Laugh out loud', 'Get the popcorn', 'Never stop learning']
    )
    if option2:
        st.text('You Selected {}'.format((option2)))
    
    option3 = st.multiselect(
        label='your selection is',
        options=['Car', 'Airplane', 'Train', 'Ship'],
        placeholder='select transportation'
    )
    st.text('you selected: {}'.format(option3))
    • 셀렉트박스나 라디오 버튼으로 사용자 선택 받기
    • 복수 선택도 가능 (multiselect)


    📌 슬라이더와 입력창, 파일 업로더

    st.divider()
    st.subheader('Slider')
    score = st.slider('Your score is...', 0, 100, 1)
    st.text('Score: {}'.format(score))
    
    from datetime import time
    start_time, end_time = st.slider(
        'Working time is...',
        min_value=time(0), max_value=time(23),
        value=(time(8), time(18)),
        format='HH:mm'
    )
    st.text('Working time: {}, {}'.format(start_time, end_time))
    
    st.divider()
    st.subheader('Input')
    string = st.text_input(
        'Your Name',
        placeholder='write down your name',
        max_chars=31
    )
    if string:
        st.text('Your name is '+string)
    
    st.divider()
    st.subheader('File uploader')
    
    file = st.file_uploader('Choose a file', type='csv', accept_multiple_files=False)
    if file is not None:
        df = pd.read_csv(file)
        st.write(df)
    • 슬라이더로 점수나 시간 등 입력 받기
    • 텍스트 입력창 / 파일 업로드 지원


    📊 차트 및 시각화

    ✅ matplotlib + seaborn

    st.divider()
    st.subheader('차트 및 이미지 표현하기')
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    df = sns.load_dataset('tips')
    fig, ax = plt.subplots()
    sns.histplot(df, x='total_bill', ax=ax, hue='time')
    st.pyplot(fig)

    ✅ plotly

    import plotly.express as px
    fig2= px.box(
        data_frame=df, x='day', y='tip',
        facet_col = 'smoker', facet_row='sex',
        width=800, height=800
    )
    st.plotly_chart(fig2)
    
    x_options = ['day', 'size']
    y_options = ['total_bill', 'tip']
    hue_options = ['smoker', 'sex']
    
    x_option = st.selectbox(
        'Select X-axis',
        index=None,
        options=x_options
    )
    y_option = st.selectbox(
        'Select Y-axis',
        index=None,
        options=y_options
    )
    hue_option = st.selectbox(
        'Select Hue',
        index=None,
        options=hue_options
    )
    
    if (x_option != None) & (y_option != None):
        if hue_option != None:
            fig3 = px.box(
                data_frame=df, x=x_option, y=y_option,
                color=hue_option, width=500
            )
        else:
            fig3 = px.box(
                data_frame=df, x=x_option, y=y_option,
                width=500
            )
        st.plotly_chart(fig3)

    → 동적으로 X축/Y축/Hue 선택해서 그래프 업데이트하는 기능도 가능!


    🖼 이미지 출력

    from PIL import Image
    
    img = Image.open('datasets/images/image1.jpg')
    st.image(img, width=300, caption='rubi')


    ✅ 마무리 정리

    기능 사용한 함수

    제목/텍스트 출력 st.title, st.text, st.markdown
    인터랙션 (버튼 등) st.button, st.checkbox, st.radio
    사용자 입력 st.slider, st.text_input, st.file_uploader
    데이터 시각화 st.pyplot, st.plotly_chart
    이미지 출력 st.image

    💬 한 줄 소감

    Streamlit은 정말 웹 개발 지식이 없어도 웹 앱을 만들 수 있는 도구예요.
    데이터 분석 결과를 공유하거나, 모델 데모를 만들고 싶은 분께 특히 강추!

     

Designed by Tistory.