Streamlit 포스팅은 BOOKK에서 발간한 "Streamlit으로 프로젝트 한방에 끝내기 with 파이썬"이라는 책을 참고하여 저의 공부 내용을 올리려고 합니다. 저자님께 감사드립니다.
저는 streamlit에 가입하고 github에 연동까지 한 상태입니다. 이 내용은 가입할 때 알아서 안내해줍니다. ㅎㅎ
Streamlit • A faster way to build and share data apps
Streamlit is an open-source app framework for Machine Learning and Data Science teams. Create beautiful web apps in minutes.
streamlit.io
라이브러리 설치
- VS code를 열어 가상 환경에 접속합니다. (terminal - new terminal - git bash 모드)
virtualenv venv
source venv/Scripts/activate
- 새 파일을 만들고 나서 requirements.txt라고 파일 명을 입력합니다. 그리고 내용에 다음을 입력합니다.
sktime
pmdarima
pandas
matplotlib
seaborn
plotly
scikit-learn
yfinance
lightgbm
prophet
statsmodels
streamlit
geopandas
folium
xmltodict
streamlit-option-menu
millify
pingouin
jupyterlab
- terminal에 다음 명령어를 입력하여 라이브러리를 설치합니다. pythpn에서 라이브러리를 설치하는 방법으로는 1) pip install 라이브러리명 을 입력하는 방법과, 2) requirements.txt파일안에 라이브러리를 입력하고 다음 명령어를 실행하는 방법이 있습니다.
pip install -r requirements.txt
Streamlit 실행하기
- terminal에 다음을 입력하여 Streamlit이 잘 작동하는 지 확인합니다.
streamlit hello
- 새 창이 뜹니다! 만약 뜨지 않는다면 Network URL로 접속해보세요.
- Streamlit이 잘 작동하고 있음을 확인했습니다. 브라우저 창에서 보이는 것처럼 멋진 나의 대시보드를 우리도 만들 수 있겠죠!
- 그리고 언제나 공식 문서를 친구처럼 친하게 둡니다.
https://docs.streamlit.io/library/api-reference/write-magic
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
- 공식 문서의 API reference 코드를 입력하며 공부하겠습니다.
st.write
- 새 파일을 생성한 후 [001]_st.write.py라고 이름을 붙이겠습니다.
- st.write
import streamlit as st
st.write('Hello, *World!* :sunglasses:')
- 실행은 terminal에 다음과 같이 입력합니다.
streamlit run [001]_st.write.py
- 새로 뜨는 창에 다음처럼 출력이 됩니다.
- 마크다운 형식이 적용되고, 이모지도 이렇게 재치있게 나오네요!
- 그리고 string 뿐만 아니라 데이터프레임, 숫자 등도 적용할 수 있습니다.
import streamlit as st
import pandas as pd
st.write(21)
st.write(pd.DataFrame({
'first column': [1, 2, 3, 4],
'second column': [10, 20, 30, 40],
}))
- 동시에 여러 type의 데이터를 입력해도 됩니다.
data_frame = pd.DataFrame({
'first column' : [1, 2, 3, 4],
'second column' : [10, 20, 30, 40]
})
st.write('2 + 3 = ', 5)
st.write('Below is a DataFrame:', data_frame, 'Above is a dataframe.')
- 차트도 보여줄 수 있습니다.
import streamlit as st
import pandas as pd
import numpy as np
import altair as alt
df = pd.DataFrame(
np.random.randn(200, 3),
columns=['a', 'b', 'c'])
c = alt.Chart(df).mark_circle().encode(
x='a', y='b', size='c', color='c', tooltip=['a', 'b', 'c'])
st.write(c)
- 짧은 코드로 그럴듯한 결과물이 생깁니다. 이것이 streamlit의 경쟁력입니다.
Text elements
st.martdoun
- 마크다운은 github의 양식을 따릅니다. 이모지도 함께 제공되는데, 다음 주소로 들어가면 그 list가 나와 있습니다.
https://share.streamlit.io/streamlit/emoji-shortcodes
https://share.streamlit.io/streamlit/emoji-shortcodes
share.streamlit.io
- 연습해보겠습니다.
import streamlit as st
st.markdown('Streamlit is **_really_ cool**.')
st.markdown("This text is :red[colored red], and this is **:blue[colored]** and bold.")
st.markdown(":green[$\sqrt{x^2+y^2}=1$] is a Pythagorean identity. :pencil:")
st.title / st.header / st.subheader / st.caption
st.title('This is a :red[title]. :first_quarter_moon_with_face:')
st.header('A **header** with _italics_ :blue[colors] and emojis :mechanic:')
st.subheader('A subheader with :yellow[colors] and emoji :unicorn_face:')
st.caption("This is a string that *explains something* above.")
st.code
code = '''def hello():
print("Hello, Streamlit!")'''
st.code(code, language='python')
st.text
st.text('Enjoy coding!')
st.latex
st.latex(r'''
a + ar + a r^2 + a r^3 + \cdots + a r^{n-1} =
\sum_{k=0}^{n-1} ar^k =
a \left(\frac{1-r^{n}}{1-r}\right)
''')
st.divider
- st.write("---") 와 같이 선을 그어줍니다.
st.divider()
st.text("STARBUCKS")
st.write("---")
많이 익숙해졌나요? 나중에는 이러한 것을 html에 적용해보겠습니다.
다음 포스팅에서는 데이터를 표현하는 것을 연습하겠습니다.
오늘도 감사합니다!
'Python > Streamlit' 카테고리의 다른 글
[Streamlit]_잘 만들었으면 자랑해야지! 웹 배포하기 (0) | 2023.09.07 |
---|---|
[Streamlit]_쉽고 예쁘게 웹을 꾸밀 수 있다고!? - All about **Columns**(1) (0) | 2023.08.15 |
[Streamlit]_쉽고 예쁘게 웹을 꾸밀 수 있다고!? - 데이터 표현하기 (0) | 2023.08.13 |
[Streamlit]_Hello World 출력하기 (0) | 2023.07.27 |