Streamlit/이론

144. [Python] [Streamlit] : Streamlit(스트림릿) 차트 그리기(1)

천재단미 2025. 2. 4. 09:47
728x90
반응형

 

 

데이터를 시각화하여 정보를 전달하는 것은 데이터 분석의 핵심 요소 중 하나입니다.

Streamlit은 Matplotlib, Seaborn, 그리고 Pandas와 같은 시각화 라이브러리와 통합되어 있어 차트를 간단히 표현할 수 있습니다. 

 

 

🛠️ 코드 설명

1️⃣ 필요한 라이브러리 설치 및 설정

import pandas as pd
import streamlit as st
import matplotlib.pyplot as plt
import seaborn as sb
from matplotlib import rc

# 한글 폰트 설정 (Mac 기준)
rc('font', family='AppleGothic')
plt.rcParams['axes.unicode_minus'] = False

 

이 코드에서는 데이터 시각화에 필요한 matplotlib과 seaborn을 불러오고, 한글 깨짐 방지를 위한 폰트 설정을 추가합니다.


2️⃣ Streamlit 기본 구조

Streamlit 애플리케이션의 기본 구조는 다음과 같습니다:

def main():
    st.title('차트 그리기1')
    df = pd.read_csv('data/iris.csv')  # Iris 데이터셋 로드
    st.dataframe(df)  # 데이터프레임 출력

  • st.title: 페이지 제목 설정
  • st.dataframe: DataFrame 데이터를 웹에서 테이블 형태로 출력

3️⃣ 산점도(Scatter Plot) 생성

코드 :

st.text('스캐터 플롯')
fig1 = plt.figure()
plt.scatter(data=df, x='petal_length', y='petal_width')
plt.title('꽃잎 길이 대 꽃잎 너비')
plt.xlabel('꽃잎 길이')
plt.ylabel('꽃잎 너비')
st.pyplot(fig1)

출력

이 코드는 matplotlib를 활용해 petal_length와 petal_width의 관계를 산점도로 시각화합니다. 산점도는 두 변수 간의 관계를 직관적으로 이해하기에 적합합니다.


4️⃣ Seaborn 회귀선 시각화

코드 :

fig2 = plt.figure()
sb.regplot(data=df, x='petal_length', y='petal_width')
st.pyplot(fig2)

 

출력

Seaborn의 regplot을 사용하여 두 변수 간의 상관관계를 시각화하고, 회귀선을 추가하여 경향성을 강조합니다.


5️⃣ 히스토그램(Histogram) 생성

단일 히스토그램 :

st.text('꽃잎 길이에 대한 히스토그램')
fig3 = plt.figure()
plt.hist(data=df, x='petal_length', rwidth=0.8)
st.pyplot(fig3)

 

출력

 

Iris 데이터의 petal_length 분포를 히스토그램으로 표현합니다. rwidth를 설정해 막대 간격을 조정합니다.

 

여러 히스토그램 비교 :

fig5 = plt.figure()
plt.subplot(1, 2, 1)
plt.hist(data=df, x='petal_length', rwidth=0.8)

plt.subplot(1, 2, 2)
plt.hist(data=df, x='petal_length', rwidth=0.8, bins=20)
st.pyplot(fig5)


6️⃣ 범주형 데이터의 막대 차트

Countplot :

fig6 = plt.figure()
sb.countplot(data=df, x='species')
st.pyplot(fig6)

Pandas 막대 그래프 :

fig7 = plt.figure()
df['species'].value_counts().plot(kind='bar')
st.pyplot(fig7)


7️⃣ 상관 관계 히트맵(Heatmap)

코드 :

st.dataframe(df.corr(numeric_only=True))
fig8 = plt.figure()
sb.heatmap(df.corr(numeric_only=True), annot=True, vmin=-1, vmax=1, cmap='coolwarm')
st.pyplot(fig8)

 

출력

 

heatmap은 변수 간의 상관 관계를 직관적으로 보여줍니다. annot=True를 설정하여 각 셀에 상관 계수를 표시합니다.

 

 

728x90
반응형
home top bottom
}