Streamlit

python(파이썬)의 streamlit(스트림릿)에서 다양한 데이터 차트 그리기 2

HooSL 2022. 1. 10. 17:36

스트림릿과 차트그리기에 필요한 라이브러리 import 해줍니다.

import streamlit as st
import pandas as pd

#해당 라이브러리는 설치가 필요합니다.
import altair as alt
import plotly.express as px

라이브러리 설치는

https://altair-viz.github.io/

 

Altair: Declarative Visualization in Python — Altair 4.2.0 documentation

© Copyright 2016-2020, Altair Developers.

altair-viz.github.io

https://plotly.com/python/getting-started/

 

Getting Started

Getting Started with Plotly for Python.

plotly.com

 

def main():
    
    df1 = pd.read_csv('data/lang_data.csv')
    st.dataframe(df1)

    print(df1.columns[1:])

    lang_list = df1.columns[1:]

    choice_list=st.multiselect('언어를 선택하세요',lang_list)

    print(choice_list)

    if len(choice_list) != 0:
        # 유저가 선택한 언어만, 차트를 그리려고 합니다.
        df_selected = df1[choice_list]

        #스트림릿이 제공하는 라인 차트
        st.line_chart(df_selected)

        #스트림릿이 제공하는 영역차트
        st.area_chart(df_selected)
    df2 = pd.read_csv('data/iris.csv')

    #스트림릿이 제공하는 bar 차트
    df_selected2 = df2[ ['sepal_length','petal_length'] ]
    st.bar_chart(df_selected2)

    #Altair 이용
    #x 축과 y축 설정 + color 또는 size로 차트를 풍성하게 표현
    chart = alt.Chart(df2).mark_circle().encode(x='petal_length',y='petal_width',color='species')
    st.altair_chart(chart)

    #스트림릿의 map 차트
    df3 = pd.read_csv('data/location.csv',index_col=0)
    st.dataframe(df3)
    st.map(data=df3)

    #plotly 를 이용한 차트 그리기
    df4 = pd.read_csv('data/prog_languages_data.csv',index_col=0)
    st.dataframe(df4)

    #plotly의 pie 차트
    fig1 = px.pie(df4,'lang','Sum',title='각 언어별 파이차트')
    st.plotly_chart(fig1)

    #plotly의 bar 차트
    df4_sorted = df4.sort_values('Sum',ascending=False)
    fig2 = px.bar(df4_sorted,x='lang',y='Sum')
    st.plotly_chart(fig2)
    
if __name__ =='__main__':
    main()