Web/Streamlit

[Web] Streamlit 라이브러리 소개 및 기본문법

skwkiix 2023. 9. 11. 10:39
728x90

Streamlit

Streamlit은 웹 애플리케이션(대시보드)을 쉽게 만들고 공유하기 위한 파이썬 라이브러리이다.

https://docs.streamlit.io/

 

Streamlit Docs

Join the community Streamlit is more than just a way to make data apps, it's also a community of creators that share their apps and ideas and help each other make their work better. Please come join us on the community forum. We love to hear your questions

docs.streamlit.io

Streamlit을 사용하면 데이터 시각화, 대시보드, 프로토 타입, 간단한 웹 애플리케이션 등을 Python 코드로 간단히 작성하여 구현할 수 있으며, 배포가 간단하고 다른 시각화 라이브러리와 함께 시각화를 간단히 구현할 수 있는 장점이 있다.


사용 방법


01. 라이브러리 준비

streamlit 라이브러리와 시각화 라이브러리 등 기타 필요한 라이브를 임포트 해준다.

# -*- coding: UTF-8 -*-
import streamlit as st
import seaborn as sns
import pandas as pd 
import matplotlib.pyplot as plt
import plotly.graph_objects as go
from plotly.subplots import make_subplots

 

02. 구현 방법

 - 터미널에서 streamlit run 앱이름.py 를 입력한다.

- command + 클릭으로 실행한다. (MAC 기준)

 


기본 문법


01. 쓰기 문법

title, text, text_input, write

- st.title("내용")

- st.text("내용")

- st.text_input("제목", "내용")

- st.write("내용")

st.title("Hello World!")
st.text("Hello world2")
title = st.text_input('Movie title', 'Life of Brian')
st.write('The current movie title is', title)

스트림릿 실행화면

 

02. 마크다운 문법

streamlit 은 st.markdown 을 이용해 마크다운 문법을 적용할 수 있다.

 st.markdown('이 텍스트는 :red[빨간 글자], 굵게 하기 **:blue[파란 글자]** ')
 st.markdown("""
    ## Chapter 2
    - 피타고라스 정리 :blue[$\sqrt{x^2+y^2}=1$] 
    """)

 


03. 데이터프레임 불러오는 문법

st.dataframe() 으로 판다스 문법을 적용하여 데이터 프레임을 구현할 수 있다.

st.title("데이터 프레임")
df = sns.load_dataset('iris')
st.dataframe(df.head(50))
st.write(df.head(50))

04. 동적 지표 구현 문법

st.metric() 은 특정 값을 표시하고, 그 값을 시각적으로 보여주는 기능이다.

lable, value, delta 등 주요 파라미터는 아래 공식문서를 참조한다.

https://docs.streamlit.io/library/api-reference/data/st.metric

 

Streamlit Docs

Join the community Streamlit is more than just a way to make data apps, it's also a community of creators that share their apps and ideas and help each other make their work better. Please come join us on the community forum. We love to hear your questions

docs.streamlit.io

tips = sns.load_dataset('tips')
tip_max = tips['tip'].max()
tip_min = tips['tip'].min()
st.metric(label = "Max Tip", value = tip_max, delta=tip_max - tip_min)
st.table(tips.describe())

st.metric 실행 화면


05. 시각화 구현 문법

st.pyplot() - matplotlib, seaborn

st.plotly_chart()

 

https://docs.streamlit.io/library/api-reference/charts/st.pyplot

 

Streamlit Docs

Join the community Streamlit is more than just a way to make data apps, it's also a community of creators that share their apps and ideas and help each other make their work better. Please come join us on the community forum. We love to hear your questions

docs.streamlit.io

  • matplotlib
m_tips = tips.loc[tips['sex'] == 'Male', :]
f_tips = tips.loc[tips['sex'] == 'Female', :]

fig, ax = plt.subplots(ncols=2, figsize=(10, 6), sharex = True, sharey=True)
ax[0].scatter(x = m_tips['total_bill'], y = m_tips['tip'])
ax[0].set_title('Male')
ax[0].set_xlabel('Total Bill')

ax[1].scatter(x = f_tips['total_bill'], y = f_tips['tip'])
ax[1].set_title('Female')
    
fig.supxlabel('Total Bill($)')
fig.supylabel('Tip($)')

st.pyplot(fig)

 

  • seaborn
 ## Seaborn 
st.write('*' * 50)
m_tips = tips.loc[tips['sex'] == 'Male', :]
f_tips = tips.loc[tips['sex'] == 'Female', :]
fig1, ax = plt.subplots(ncols=2, figsize=(10, 6), sharex = True, sharey=True)
sns.scatterplot(data = m_tips, x = 'total_bill', y = 'tip', hue='smoker',  ax=ax[0])
ax[0].set_title('Male')
ax[0].set_xlabel('Total_Bill')

fig1.supxlabel('Total Bill($)')
fig1.supylabel('Tip($)')

st.pyplot(fig1)

 

  • plotly

plotly 라이브러리를 이용한 시각화는 별도로 st.plotly_chart()를 사용해준다.

 

https://docs.streamlit.io/library/api-reference/charts/st.plotly_chart

 

Streamlit Docs

Join the community Streamlit is more than just a way to make data apps, it's also a community of creators that share their apps and ideas and help each other make their work better. Please come join us on the community forum. We love to hear your questions

docs.streamlit.io

## plotly
fig = make_subplots(rows = 1,
                    cols = 2,
                    subplot_titles=('Male', 'Female'),
                    shared_yaxes=True,
                    shared_xaxes=True,
                    x_title='Total Bill($)'
                    )
fig.add_trace(go.Scatter(x = m_tips['total_bill'], y = m_tips['tip'], mode='markers'), row=1, col=1)
fig.add_trace(go.Scatter(x = f_tips['total_bill'], y = f_tips['tip'], mode='markers'), row=1, col=2)
fig.update_yaxes(title_text="Tip($)", row=1, col=1)
fig.update_xaxes(range=[0, 60])
fig.update_layout(showlegend=False)

## Streamlit 위젯
# Display visualization
st.plotly_chart(fig, use_container_width=True)


 

위의 예시 코드를 함수로 구현한 전체코드는 아래와 같다.

# -*- coding: UTF-8 -*-
import streamlit as st
import seaborn as sns
import pandas as pd 
import matplotlib.pyplot as plt
import plotly.graph_objects as go
from plotly.subplots import make_subplots

def main():
    st.title("Hello World!")

    st.text("Hello world2")

    title = st.text_input('Movie title', 'Life of Brian')
    st.write('The current movie title is', title)
    
    # ch05
    # 마크다운
    st.markdown('이 텍스트는 :red[빨간 글자], 굵게 하기 **:blue[파란 글자]** ')
    st.write('-' * 50)
    st.markdown("""
    ## Chapter 2
    - 피타고라스 정리 :blue[$\sqrt{x^2+y^2}=1$] 
    """)
    st.write('-' * 50)
    st.markdown("## Chapter 3. ddddd \n"
                "- Streamlit **정말 좋네요!!** \n"
                "   * 이 텍스트는 :red[빨간 글자], 굵게 하기 **:blue[파란 글자]**"
    )

    # HTML CSS 스타일 적용! 
    st.title("HTML CSS 마크다운 적용")
    html_css = """
    <style>
      th, td {
        border-bottom: 1px solid #ddd;
      }
    </style>

    <table>
      <thead>
        <tr>
          <th>이름</th>
          <th>나이</th>
          <th>직업</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Evan</td>
          <td>25</td>
          <td>데이터 분석가</td>
        </tr>
        <tr>
          <td>Sarah</td>
          <td>25</td>
          <td>프로덕트 오너</td>
        </tr>
      </tbody>
    </table>
    """

    st.markdown(html_css, unsafe_allow_html=True)

    ## 데이터 프레임
    st.title("데이터 프레임")
    df = sns.load_dataset('iris')
    st.dataframe(df.head(50))
    st.write(df.head(50))

    ## metric 
    tips = sns.load_dataset('tips')
    tip_max = tips['tip'].max()
    tip_min = tips['tip'].min()
    st.metric(label = "Max Tip", value = tip_max, delta=tip_max - tip_min)
    st.table(tips.describe())

    ## 시각화 matplotlib
    ## 테스트 
    m_tips = tips.loc[tips['sex'] == 'Male', :]
    f_tips = tips.loc[tips['sex'] == 'Female', :]

    st.dataframe(f_tips)

    fig, ax = plt.subplots(ncols=2, figsize=(10, 6), sharex = True, sharey=True)
    ax[0].scatter(x = m_tips['total_bill'], y = m_tips['tip'])
    ax[0].set_title('Male')
    ax[0].set_xlabel('Total Bill')

    ax[1].scatter(x = f_tips['total_bill'], y = f_tips['tip'])
    ax[1].set_title('Female')
    
    fig.supxlabel('Total Bill($)')
    fig.supylabel('Tip($)')
    # fig = 도화지
    # ax = 색연필, 물감, 크레파스

    st.pyplot(fig)

    ## Seaborn 
    st.write('*' * 50)
    m_tips = tips.loc[tips['sex'] == 'Male', :]
    f_tips = tips.loc[tips['sex'] == 'Female', :]
    fig1, ax = plt.subplots(ncols=2, figsize=(10, 6), sharex = True, sharey=True)
    sns.scatterplot(data = m_tips, x = 'total_bill', y = 'tip', hue='smoker',  ax=ax[0])
    ax[0].set_title('Male')
    ax[0].set_xlabel('Total_Bill')

    fig1.supxlabel('Total Bill($)')
    fig1.supylabel('Tip($)')

    st.pyplot(fig1)

    ## plotly
    fig = make_subplots(rows = 1,
                        cols = 2,
                        subplot_titles=('Male', 'Female'),
                        shared_yaxes=True,
                        shared_xaxes=True,
                        x_title='Total Bill($)'
                        )
    fig.add_trace(go.Scatter(x = m_tips['total_bill'], y = m_tips['tip'], mode='markers'), row=1, col=1)
    fig.add_trace(go.Scatter(x = f_tips['total_bill'], y = f_tips['tip'], mode='markers'), row=1, col=2)
    fig.update_yaxes(title_text="Tip($)", row=1, col=1)
    fig.update_xaxes(range=[0, 60])
    fig.update_layout(showlegend=False)

    ## Streamlit 위젯

    # Display visualization
    st.plotly_chart(fig, use_container_width=True)


if __name__ == "__main__":
    main()
728x90