행위

"Python streamlit dashboard"의 두 판 사이의 차이

DB CAFE

1번째 줄: 1번째 줄:
 
= 파이썬 Streamlit 대시보드 개발 =
 
= 파이썬 Streamlit 대시보드 개발 =
 
== 설치 ==
 
== 설치 ==
https://blog.zarathu.com/posts/2023-02-01-streamlit/
+
- Install command
 +
<source lang=python>
 +
$ pip install streamlit
 +
$ streamlit hello
 +
</source>
 +
 
 +
- 사용통계 출력시 아래 위치 옵션 변경
 +
<source lang=python>
 +
~/.streamlit/config.toml, creating that file if necessary:
 +
 
 +
[browser]
 +
gatherUsageStats = false
 +
</source>
 +
 
 +
 
 +
* github repository: https://github.com/streamlit/streamlit
 +
* document: https://docs.streamlit.io/
 +
* tutorial: https://docs.streamlit.io/en/stable/getting_started.html
 +
 
 +
  
 
== 실행 방법 ==
 
== 실행 방법 ==
7번째 줄: 26번째 줄:
 
streamlit run test.py
 
streamlit run test.py
 
</source>
 
</source>
 +
 +
* Local URL: http://localhost:8501
 +
* Network URL: http://192.168.35.186:8501
 +
  
 
== Streamlit 샘플 ==
 
== Streamlit 샘플 ==
18번째 줄: 41번째 줄:
 
<source lang=python>
 
<source lang=python>
 
streamlit run app.py  
 
streamlit run app.py  
 +
</source>
 +
 +
== Streamlit 샘플2 ==
 +
=== first_app.py 생성 ===​
 +
import streamlit as st
 +
import pandas as pd
 +
 +
=== 타이틀 생성 ===
 +
<source lang=python>
 +
st.title('My first app')
 +
 +
st.write("Here's our first attempt at using data to create a table:")
 +
 +
st.write(pd.DataFrame({
 +
    'first column': [1, 2, 3, 4],
 +
    'second column': [10, 20, 30, 40]
 +
}))
 +
 +
</source>
 +
* st.write()는 str 타입뿐만 아니라 pandas의 DataFrame 도 write 가능.
 +
 +
=== 스트림릿 실행 ===
 +
<source lang=python>
 +
$ streamlit run first_app.py
 
</source>
 
</source>
  
33번째 줄: 80번째 줄:
  
 
== 레이아웃 만들기 ==
 
== 레이아웃 만들기 ==
 
 
* 레이아웃으로 웹페이지 분할
 
* 레이아웃으로 웹페이지 분할
 
* columns 함수  
 
* columns 함수  
59번째 줄: 105번째 줄:
  
  
github repository: https://github.com/streamlit/streamlit
+
== Data Visualization ==
tutorial: https://docs.streamlit.io/en/stable/getting_started.html
+
=== line chart 그리기 ===
+
* st.line_chart() 메서드로 line chart 추가
streamlit는 파이썬 기반으로 손쉽게 웹 어플리케이션을 개발하는 오픈소스입니다. 웹에 대한 이해 없이도 간단한 파이썬 코드만으로 대부분의 웹 어플리케이션 구현이 가능합니다. 간단한 데이터 Visualization 혹은 인공지능 모델 시연 등 여러 분야에 활용될 수 있을 것 같습니다.
+
<source lang=python>
 
 
Installation
 
 
- Install command
 
$ pip install streamlit
 
$ streamlit hello
 
  👋 Welcome to Streamlit!
 
 
 
  If you're one of our development partners or you're interested in getting
 
  personal technical support or Streamlit updates, please enter your email
 
  address below. Otherwise, you may leave the field blank.
 
 
 
  Email: sh951011@gmail.com
 
 
 
  Privacy Policy:
 
  As an open source project, we collect usage statistics. We cannot see and do
 
  not store information contained in Streamlit apps. You can find out more by
 
  reading our privacy policy at: https://streamlit.io/privacy-policy
 
 
 
  If you'd like to opt out of usage statistics, add the following to
 
  ~/.streamlit/config.toml, creating that file if necessary:
 
 
 
    [browser]
 
    gatherUsageStats = false
 
 
 
 
 
  Welcome to Streamlit. Check out our demo in your browser.
 
 
 
  Local URL: http://localhost:8501
 
  Network URL: http://192.168.35.186:8501
 
 
 
  Ready to create your own Python apps super quickly?
 
  Head over to https://docs.streamlit.io
 
 
 
  May you create awesome apps!
 
 
Get Started
 
 
Create your first Streamlit app
 
 
1.  first_app.py를 만들고 streamlit를 import 합니다.​
 
import streamlit as st
 
import pandas as pd
 
2. st.write()을 사용합니다.
 
 
 
st.title('My first app')
 
st.write("Here's our first attempt at using data to create a table:")
 
st.write(pd.DataFrame({
 
    'first column': [1, 2, 3, 4],
 
    'second column': [10, 20, 30, 40]
 
}))
 
st.write()는 str 타입뿐만 아니라 pandas의 DataFrame도 손쉽게 write 할 수 있습니다.
 
 
3. Run by streamlit
 
$ streamlit run first_app.py
 
 
여기까지만 해도 streamlit을 활용하면 상당히 편리하게 데이터를 보여줄 수 있습니다. 다음으로는 streamlit을 이용해서 데이터 visualization하는 방법에 대해 살펴보겠습니다.
 
 
Draw charts and maps
 
 
웹 어플리케이션에 bar chart, line chart, map을 추가하는 법을 대해 배워봅시다.
 
 
- Draw a line chart
 
 
파이썬에서는 matplotlib과 같은 라이브러리를 이용하면 쉽게 line chart를 그릴 수 있습니다만, 웹 어플리케이션에서 이런 이미지를 띄우려면 상황에 따라 복잡해질 수도 있습니다. 하지만 streamlit에서는 st.line_chart() 메서드로 편리하게 line chart를 추가할 수 있습니다.
 
 
 
chart_data = pd.DataFrame(
 
chart_data = pd.DataFrame(
 
     np.random.randn(20, 3),
 
     np.random.randn(20, 3),
135번째 줄: 114번째 줄:
  
 
st.line_chart(chart_data)
 
st.line_chart(chart_data)
+
</source>
- Plot a map
+
 
+
=== map 그리기 ===
지도 역시 마찬가지입니다. 노 베이스로 지도를 그린다면 굉장히 어렵겠지만, streamlit에서는 지도 역시 st.map() 메서드로 편리하게 지원합니다.
+
* st.map() 메서드 사용.
 +
<source lang=python>
 
map_data = pd.DataFrame(
 
map_data = pd.DataFrame(
 
     np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
 
     np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
144번째 줄: 124번째 줄:
  
 
st.map(map_data)
 
st.map(map_data)
+
</source>
 
Add interactivity with widgets
 
 
streamlit은 체크박스, 버튼, 슬라이더 등 여러 interactive 위젯 API를 제공합니다. streamlit에서 제공하는 모든 API는 여기에서 확인할 수 있습니다.
 
 
- Checkbox show/hide data
 
 
st.checkbox()를 이용하면 체크박스를 이용해서 데이터 show/hide 설정을 할 수 있습니다. st.checkbox()는 위젯명을 argument로 받아서 처리합니다.
 
  
 +
=== Checkbox show/hide data ===
 +
​* st.checkbox() 이용, 체크박스를 이용해서 데이터 show/hide 설정.
 +
* st.checkbox()는 위젯명을 argument로 받아서 처리.
 +
<source lang=python>
 
if st.checkbox('Show dataframe'):
 
if st.checkbox('Show dataframe'):
 
     chart_data = pd.DataFrame(
 
     chart_data = pd.DataFrame(
160번째 줄: 136번째 줄:
  
 
     chart_data
 
     chart_data
 +
 +
</source>
 +
 
   
 
   
 
 
- Selectbox for options
+
=== Selectbox ===
+
* st.selectbox()는 pandas.Series를 입력으로 받아서 옵션 선택.
st.selectbox()는 pandas.Series를 입력으로 받아서 옵션을 선택받게 할 수 있습니다.
+
 
 +
<source lang=python>
 
import streamlit as st
 
import streamlit as st
 
import pandas as pd
 
import pandas as pd
174번째 줄: 154번째 줄:
  
 
'You selected: ', option
 
'You selected: ', option
   
+
</source>
Lay out your app
+
  ​
+
==== Selectbox를 사이드로 이동 ====
웹 어플리케이션을 구현할 때 중요한 점 중 하나를 레이아웃입니다. 어떻게 화면을 구성하냐에 따라서 더 깔끔하고 직관적이게 보일 수가 있습니다. streamlit은 이런 기능 또한 손쉽게 다룰 수 있습니다.
+
<source lang=python>
 
- Selectbox를 사이드로
 
 
방금 앞에서 했던 selectbox를 사이드로 옮기고 싶다면 어떻게 해야할까요? streamlit에서는 아래와 같이 간단하게 구현 가능합니다.
 
 
import streamlit as st
 
import streamlit as st
 
import pandas as pd
 
import pandas as pd
191번째 줄: 167번째 줄:
  
 
'You selected: ', option
 
'You selected: ', option
 +
 +
</source>
 
   
 
   
위와 같이 streamlit에서 제공하는 대부분의 element는 st.sidebar. [element_name]() 포맷으로 사용 가능합니다. 위의 위젯 외에도 button, expander 등 여러 위젯이 있으니 다양하게 사용해보시길 바랍니다.
+
* streamlit에서 제공하는 대부분의 element는 st.sidebar. [element_name]() 포맷으로 사용 가능.  
 +
* 위의 위젯 외에도 button, expander 등 여러 위젯 사용 가능.
 
 
Show progress
+
=== progress 진행현황표시 ===
+
* st.progress()이용, 웹이지에 진행현황을 표시.  
이번에는 웹페이지에 진행현황을 표시해봅시다. st.progress()를 이용하면 아래처럼 쉽게 사용이 가능합니다.
+
<source lang=python>
 
import time
 
import time
  
212번째 줄: 191번째 줄:
  
 
'...and now we\'re done!
 
'...and now we\'re done!
 +
</source>
 
   
 
   
 +
=== APP Deploy , Manage , Share ===
 +
* streamlit으로 개발한 app은 Streamlit Cloud로 deploy, manage, share 가능.
 +
* 현재 Streamlit Cloud는 초대를 받은 멤버에 한해서 사용이 가능합니다.
 +
* Request an invite에 몇 가지 사항을 제출하고 사용.
 
 
Share your app
+
==== 3스텝으로 구현 가능 ====
+
​1. Put your app in a public Github repo (and make sure it has a requirements.txt!)
streamlit으로 개발한 app은 Streamlit Cloud로 deploy, manage, share가 모두 가능합니다. 현재 Streamlit Cloud는 초대를 받은 멤버에 한해서 사용이 가능합니다. Request an invite에 몇 가지 사항을 제출하고 사용해주시면 됩니다.
 
 
다음 3 스텝으로 간단하게 구현 가능합니다.
 
 
1. Put your app in a public Github repo (and make sure it has a requirements.txt!)
 
 
2. Sign into share.streamlit.io
 
2. Sign into share.streamlit.io
 
3. Click ‘Deploy an app’ and then paste in your GitHub URL
 
3. Click ‘Deploy an app’ and then paste in your GitHub URL
230번째 줄: 209번째 줄:
  
 
https://analyticsindiamag.com/ai-mysteries/build-and-deploy-your-first-real-time-dashboard-with-streamlit/
 
https://analyticsindiamag.com/ai-mysteries/build-and-deploy-your-first-real-time-dashboard-with-streamlit/
 
  
 
https://www.geeksforgeeks.org/create-interactive-dashboard-in-python-using-streamlit/
 
https://www.geeksforgeeks.org/create-interactive-dashboard-in-python-using-streamlit/

2024년 8월 21일 (수) 12:44 판

thumb_up 추천메뉴 바로가기


1 파이썬 Streamlit 대시보드 개발[편집]

1.1 설치[편집]

- Install command

$ pip install streamlit
$ streamlit hello

- 사용통계 출력시 아래 위치 옵션 변경

~/.streamlit/config.toml, creating that file if necessary:

[browser]
gatherUsageStats = false


1.2 실행 방법[편집]

streamlit run test.py


1.3 Streamlit 샘플[편집]

  • 샘플 소스
import streamlit as st
st.title('Hello Streamlit')
  • 실행
streamlit run app.py

1.4 Streamlit 샘플2[편집]

=== first_app.py 생성 ===​ import streamlit as st import pandas as pd

1.4.1 타이틀 생성[편집]

st.title('My first app')

st.write("Here's our first attempt at using data to create a table:")

st.write(pd.DataFrame({
    'first column': [1, 2, 3, 4],
    'second column': [10, 20, 30, 40]
}))
  • st.write()는 str 타입뿐만 아니라 pandas의 DataFrame 도 write 가능.

1.4.2 스트림릿 실행[편집]

$ streamlit run first_app.py

1.5 문자열 관련[편집]

import streamlit as st

# 타이틀
st.title('this is title')
# 헤더 
st.header('this is header')
# 서브헤더
st.subheader('this is subheader')

1.6 레이아웃 만들기[편집]

  • 레이아웃으로 웹페이지 분할
  • columns 함수
import streamlit as st

col1,col2 = st.columns([2,3])
# 공간을 2:3 으로 분할하여 col1과 col2 컬럼 생성.  

with col1 :
  # column 1 에 담을 내용
  st.title('here is column1')
with col2 :
  # column 2 에 담을 내용
  st.title('here is column2')
  st.checkbox('this is checkbox1 in col2 ')


# with 구문 말고 다르게 사용 가능 
col1.subheader(' i am column1  subheader !! ')
col2.checkbox('this is checkbox2 in col2 ') 
# => 위에 with col2: 안의 내용과 같은 기능


1.7 Data Visualization[편집]

1.7.1 line chart 그리기[편집]

​* st.line_chart() 메서드로 line chart 추가

chart_data = pd.DataFrame(
     np.random.randn(20, 3),
     columns=['a', 'b', 'c'])

st.line_chart(chart_data)

1.7.2 map 그리기[편집]

​* st.map() 메서드 사용.

map_data = pd.DataFrame(
    np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
    columns=['lat', 'lon'])

st.map(map_data)

1.7.3 Checkbox show/hide data[편집]

​* st.checkbox() 이용, 체크박스를 이용해서 데이터 show/hide 설정.

  • st.checkbox()는 위젯명을 argument로 받아서 처리.
if st.checkbox('Show dataframe'):
    chart_data = pd.DataFrame(
       np.random.randn(20, 3),
       columns=['a', 'b', 'c'])

    chart_data


1.7.4 Selectbox[편집]

​* st.selectbox()는 pandas.Series를 입력으로 받아서 옵션 선택.

import streamlit as st
import pandas as pd

st.title('TUNiBerse')
option = st.selectbox(
    '당신의 직책을 선택해주세요.',
     pd.Series(['CEO', 'AI Engineer', 'Intern', 'Product Manager']))

'You selected: ', option

1.7.4.1 Selectbox를 사이드로 이동[편집]

import streamlit as st
import pandas as pd

st.title('TUNiBerse')
option = st.sidebar.selectbox(
    '당신의 직책을 선택해주세요.',
     pd.Series(['CEO', 'AI Engineer', 'Intern', 'Product Manager']))

'You selected: ', option
  • streamlit에서 제공하는 대부분의 element는 st.sidebar. [element_name]() 포맷으로 사용 가능.
  • 위의 위젯 외에도 button, expander 등 여러 위젯 사용 가능.

1.7.5 progress 진행현황표시[편집]

​* st.progress()이용, 웹이지에 진행현황을 표시.

import time

'Starting a long computation...'

# Add a placeholder
latest_iteration = st.empty()
bar = st.progress(0)

for i in range(100):
  # Update the progress bar with each iteration.
  latest_iteration.text(f'Iteration {i+1}')
  bar.progress(i + 1)
  time.sleep(0.1)

'...and now we\'re done!

1.7.6 APP Deploy , Manage , Share[편집]

  • streamlit으로 개발한 app은 Streamlit Cloud로 deploy, manage, share 가능.
  • 현재 Streamlit Cloud는 초대를 받은 멤버에 한해서 사용이 가능합니다.
  • Request an invite에 몇 가지 사항을 제출하고 사용.

1.7.6.1 3스텝으로 구현 가능[편집]

​1. Put your app in a public Github repo (and make sure it has a requirements.txt!) 2. Sign into share.streamlit.io 3. Click ‘Deploy an app’ and then paste in your GitHub URL