[추가] VS studio와 steamlit

고보·2024년 3월 21일

1 steamlit

  • 데이터 과학 및 머신러닝 웹 애플리케이션 빠르게 구축하는 라이브러리. 웹 개발 할 줄 모른 채 간단한 python 스크립트로 대화형 웹 앱 만들 수 있다.

2 과정

  • visual studio coide, anaconda 설치
  • C/사용자에 Streamlit이라는 폴더 만들기
  • visual studio에서 파이썬 앱 설치
  • visual studio에서 Streamlit이라는 폴더랑 연결
  • ctrl + shift + p 하고 python interpreter global
  • view- terminal - command prompt
  • base로 이동: conda activate base(혹시 여기서 문제가 생기면 anaconda가 환경 변수로 설정되어야 하는 것)
  • 가상 환경 만들기: conda create -n STR python=3.9.13
  • 가상 환경으로 이동: conda activate STR
  • 가상 환경에 streamlit 설치: pip install streamlit으로 설치
  • 필요 라이브러리 일괄 설치: streamlit 폴더에 requirement.txt에서 옮겨놓고 => pip install -r requirements.txt
  • VS streamlit 폴더에 myApp.py라는 파일 만들어서 코드 짠다
  • 실행: streamlit run myApp.py
  • 가상환경 삭제: conda env remove -n STR

3 예시

3-1

import streamlit as st
st.title('Title *Markdown* 인식')
st.header('Title *Markdown* 헤더')
st.title('Title *Markdown* 인식')
st.header('Title *Markdown* 헤더')
st.subheader('Title *Markdown* 서브')
x = 10
y = 20
st.write('x=', x, 'y=', y)
# 데이터 프레임 만들기
import pandas as pd
df = pd.DataFrame({'col1': [1,2,3]})
df
st.write('데이터 프레임', df)
# 히스토그램 시각화
import matplotlib.pyplot as plt
import numpy as np
arr = np.random.normal(1, 1, size = 100)
fig, ax = plt.subplots()
ax.hist(arr, bins =20)
fig
code = '''def hello():
print('Hello, Streamlist')'''
st.code(code, language = 'python')
# 단어 색깔 지정하기
'This is :red[red]'
'This is :green[green]'
# 캡션달기
st.caption('This')
# 이모티콘
'여름엔 딱 좋아 :선글라스: '
':100: 점~'
':웃음:ㅎㅎ :+1: 최고!!'
':반짝임: 재밌다. :질문: :질문:'
# 토글 박스 만들기
option = st.selectbox('Please select in selectbox!', ('봄', '여름', '가을', '겨을'))
st.write('You selected:', option)

3-2 예시

import streamlit as st
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# 헤더 설정
_, col, _ = st.columns([2,6,2])
col.header('Streamlit 시각화')
'' #한칸 띄우기
# iris 데이터 불러오기
dfIris = sns.load_dataset('iris')
colors = {'setosa':'red', 'virginica' : 'green', 'versicolor':'blue'}
# 사이드바의 타이틀을 지정해주기
st.sidebar.title('Iris Species :벚꽃:')
# 사이드 바 만들기
with st.sidebar:
    selectX = st.selectbox("X 변수 선택:", ["sepal_length", "sepal_width", "petal_length", "petal_width"])
    ''
    selectY = st.selectbox("Y 변수 선택:", ["sepal_length", "sepal_width", "petal_length", "petal_width"])
    ''
    selectSpecies = st.multiselect(
        '붓꽃 유형 선택 (:blue[다중]):', ['setosa', 'versicolor', 'virginica'])
    #투명도 선택 가능
    selectAlpha = st.slider('alpha 설정:', 0.1, 1.0, 0.5)
# 유형별 산점도 시각화 표현
if selectSpecies:
    fig = plt.figure(figsize = (7,5))
    for aSpecies in selectSpecies:
        df = dfIris[dfIris.species == aSpecies]
        plt.scatter(df[selectX], df[selectY],
                    color = colors[aSpecies], label=aSpecies)
        plt.legend(loc='lower right')
        plt.xlabel(selectX); plt.ylabel(selectY)
        plt.title('Iris Scatter Plot')
        st.pyplot(fig)
else:
    st.warning('붓꽃의 유형을 선택해 주세요!!!')
profile
일본에서 일하는 게임 기획자. 시시해서 죽어버리지 않게, 재밌고 의미 있는 컨텐츠에 관심 있습니다. 그 도구로 데이터, AI도 찝적댑니다.

0개의 댓글