[streamlit] Streamlit에서 Pygwalker 사용하기

[출처] https://docs.kanaries.net/pygwalker/use-pygwalker-with-streamlit

 

How to Use PyGWalker with Streamlit – Kanaries

Explore data effortlessly with Pygwalker and Streamlit. Visualize, analyze, and share insights in minutes with simple drag-and-drop actions.

docs.kanaries.net

 

1. What is Pygwalker?

Pygwalker는 데이터를 데이터 탐색을 위한 시각적 인터페이스로 바꿔주는 Python 라이브러리입니다. PyGWalker는 pandas/polars/modin 데이터 프레임을 시각적 탐색을 위한 노코드 사용자 인터페이스로 전환하여 Jupyter Notebook 데이터 분석 및 데이터 시각화 워크플로우를 간소화합니다.

Pygwalker를 사용하면 코딩 기술 없이도 몇 가지 간단한 드래그 앤 드롭 동작만으로 분산형 차트, 라인 차트, 막대 차트, 히스토그램을 쉽게 생성할 수 있습니다. 데이터를 빠르고 쉽게 탐색하고 시각화하고자 하는 데이터 과학자와 분석가를 위해 특별히 설계된 강력한 도구입니다.

2. What is Streamlit?

Streamlit은 데이터 앱 구축 및 공유에 있어 또 다른 인기 있는 Python 라이브러리입니다. 몇 주가 아니라 몇 분 만에 데이터 스크립트를 웹 앱으로 전환할 수 있습니다. Streamlit을 사용하면 복잡한 웹 개발이나 코드 작성에 끝없이 시간을 소비할 필요가 없습니다. 빠르고 오픈 소스이며 완전히 무료로 제공되는 이 도구는 Python을 사용해 대화형 공유 데이터 애플리케이션을 만들 수 있는 방법입니다.

그렇다면 Pygwalker의 강력한 시각적 분석 기능으로 시각적 탐색 앱을 구축하고 Streamlit에 데이터 앱으로 게시하는 방법은 무엇일까요? 지금부터 알아봅시다!

3. Getting Started to Use Pygwalker in Streamlit

Streamlit 에서 Pygwalker 실행을 시작하기 전에 컴퓨터가 파이썬 환경(버전 3.6 이상)으로 설정되어 있는지 확인합니다. 설정이 완료되면 다음의 간단한 단계를 따르세요:

3.1. Installing Dependencies

pip install pandas
pip install pygwalker
pip install streamlit

3.2. Embedding Pygwalker in a Streamlit Application

이제 모든 종속성이 준비되었으므로 Pygwalker를 통합하는 Streamlit 애플리케이션을 만들어 보겠습니다. pygwalker_demo.py라는 새 Python 스크립트를 생성하고 다음 코드를 복사합니다:

from pygwalker.api.streamlit import StreamlitRenderer
import pandas as pd
import streamlit as st
 
# Adjust the width of the Streamlit page
st.set_page_config(
    page_title="Use Pygwalker In Streamlit",
    layout="wide"
)
# Import your data
df = pd.read_csv("https://kanaries-app.s3.ap-northeast-1.amazonaws.com/public-datasets/bike_sharing_dc.csv")
 
pyg_app = StreamlitRenderer(df)
 
pyg_app.explorer()

3.3. Exploring Data with Pygwalker in Streamlit

Streamlit 애플리케이션을 실행하고 데이터 탐색을 시작하려면 명령 프롬프트 또는 터미널에서 다음 명령을 실행하세요:

streamlit run pygwalker_demo.py

몇 가지 정보가 표시될 것입니다:

 You can now view your Streamlit app in your browser.
  Local URL: http://localhost:8501
  Network URL: http://xxx.xxx.xxx.xxx:8501

웹 브라우저에서 제공된 URL(http://localhost:8501)을 열면, 짜잔! 이제 파이그워커의 직관적인 드래그 앤 드롭 동작을 사용해 데이터와 상호 작용하고 시각화할 수 있습니다.

차트 종류를 변경하려면 Mark type 

3.4. Saving Pygwalker Chart State

pygwalker 차트의 상태를 저장하려면 다음 단계를 따르는 것만큼이나 간단합니다:

1. 차트에서 export_code 버튼을 클릭합니다.

2. Copy to clipboard 버튼 클릭

3. 복사한 코드를 필요한 위치에 Python 스크립트에 붙여넣습니다.

import pygwalker as pyg
import pandas as pd
from pygwalker.api.streamlit import StreamlitRenderer
import streamlit as st
 
# Adjust the width of the Streamlit page
st.set_page_config(
    page_title="Use Pygwalker In Streamlit",
    layout="wide"
)
 
# Add Title
st.title("Use Pygwalker In Streamlit")
 
# Import your data
df = pd.read_csv("https://kanaries-app.s3.ap-northeast-1.amazonaws.com/public-datasets/bike_sharing_dc.csv")
 
# Paste the copied Pygwalker chart code here
vis_spec = r"""{"config":[{"config":{"defaultAggregated":true,"geoms":["bar"],"coordSystem":"generic","limit":-1,"timezoneDisplayOffset":0},"encodings":{"dimensions":[{"fid":"date","name":"date","basename":"date","semanticType":"nominal","analyticType":"dimension","offset":0},{"fid":"month","name":"month","basename":"month","semanticType":"quantitative","analyticType":"dimension","offset":0},{"fid":"season","name":"season","basename":"season","semanticType":"nominal","analyticType":"dimension","offset":0},{"fid":"year","name":"year","basename":"year","semanticType":"quantitative","analyticType":"dimension","offset":0},{"fid":"holiday","name":"holiday","basename":"holiday","semanticType":"nominal","analyticType":"dimension","offset":0},{"fid":"work yes or not","name":"work yes or not","basename":"work yes or not","semanticType":"quantitative","analyticType":"dimension","offset":0},{"fid":"am or pm","name":"am or pm","basename":"am or pm","semanticType":"nominal","analyticType":"dimension","offset":0},{"fid":"Day of the week","name":"Day of the week","basename":"Day of the week","semanticType":"quantitative","analyticType":"dimension","offset":0},{"fid":"gw_mea_key_fid","name":"Measure names","analyticType":"dimension","semanticType":"nominal"}],"measures":[{"fid":"hour","name":"hour","basename":"hour","analyticType":"measure","semanticType":"quantitative","aggName":"sum","offset":0},{"fid":"temperature","name":"temperature","basename":"temperature","analyticType":"measure","semanticType":"quantitative","aggName":"sum","offset":0},{"fid":"feeling_temp","name":"feeling_temp","basename":"feeling_temp","analyticType":"measure","semanticType":"quantitative","aggName":"sum","offset":0},{"fid":"humidity","name":"humidity","basename":"humidity","analyticType":"measure","semanticType":"quantitative","aggName":"sum","offset":0},{"fid":"winspeed","name":"winspeed","basename":"winspeed","analyticType":"measure","semanticType":"quantitative","aggName":"sum","offset":0},{"fid":"casual","name":"casual","basename":"casual","analyticType":"measure","semanticType":"quantitative","aggName":"sum","offset":0},{"fid":"registered","name":"registered","basename":"registered","analyticType":"measure","semanticType":"quantitative","aggName":"sum","offset":0},{"fid":"count","name":"count","basename":"count","analyticType":"measure","semanticType":"quantitative","aggName":"sum","offset":0},{"fid":"gw_count_fid","name":"Row count","analyticType":"measure","semanticType":"quantitative","aggName":"sum","computed":true,"expression":{"op":"one","params":[],"as":"gw_count_fid"}},{"fid":"gw_mea_val_fid","name":"Measure values","analyticType":"measure","semanticType":"quantitative","aggName":"sum"}],"rows":[{"fid":"registered","name":"registered","basename":"registered","analyticType":"measure","semanticType":"quantitative","aggName":"sum","offset":0}],"columns":[{"fid":"Day of the week","name":"Day of the week","basename":"Day of the week","semanticType":"quantitative","analyticType":"dimension","offset":0}],"color":[{"fid":"season","name":"season","basename":"season","semanticType":"nominal","analyticType":"dimension","offset":0}],"opacity":[],"size":[],"shape":[],"radius":[],"theta":[],"longitude":[],"latitude":[],"geoId":[],"details":[],"filters":[],"text":[]},"layout":{"showActions":false,"showTableSummary":false,"stack":"stack","interactiveScale":false,"zeroScale":true,"size":{"mode":"auto","width":320,"height":200},"format":{},"geoKey":"name","resolve":{"x":false,"y":false,"color":false,"opacity":false,"shape":false,"size":false}},"visId":"gw_IMf4","name":"Chart 1"}],"chart_map":{},"workflow_list":[{"workflow":[{"type":"view","query":[{"op":"aggregate","groupBy":["Day of the week","season"],"measures":[{"field":"registered","agg":"sum","asFieldKey":"registered_sum"}]}]}]}],"version":"0.4.9.7"}"""

 
pyg_app = StreamlitRenderer(df, spec=vis_spec)
 
pyg_app.explorer()

4. 차트의 저장된 상태를 확인하려면 웹 페이지를 새로고침하는 것을 잊지 마세요.

vis_spec 을 지정해주면 디폴트로 보이는 차트가 정해지는 것 같다.

Pygwalker 는 엑셀, 에어테이블 등 어디에나 삽입할 수 있는 Graphic walker를 기반으로 합니다. 따라서 Pygwalker 앱에서도 이 기능을 활용하여 graphic-walker/pygwalker가 포함된 다른 플랫폼의 사용자와 협업할 수 있습니다.

4. Conclusion

PygwalkerStreamlit은 데이터를 훨씬 쉽게 탐색하고 공유할 수 있는 환상적인 도구입니다.

Pygwalker의 직관적인 인터페이스와 다양한 시각화 옵션, 데이터 앱 구축 및 공유 프로세스를 간소화하는 Streamlit의 기능을 통해 데이터 시각화 및 탐색을 위한 시각적 UI를 갖춘 데이터 앱을 빠르게 구축할 수 있습니다.

초보자든 숙련된 데이터 과학자든, Pygwalker와 Streamlit은 데이터 분석 워크플로우를 향상시키고 결과를 효과적으로 전달할 수 있도록 도와줍니다. 이제 데이터를 탐색하고 놀라운 인사이트를 전 세계와 공유하세요!

5. References