행위

"Python streamlit dashboard"의 두 판 사이의 차이

DB CAFE

(Streamlit 샘플2)
(참조 사이트)
 
(같은 사용자의 중간 판 하나는 보이지 않습니다)
1번째 줄: 1번째 줄:
= 파이썬 Streamlit 대시보드 개발 =
+
== streamlit dashbaord 개발 ==
== 설치 ==
 
- Install command
 
<source lang=python>
 
$ pip install streamlit
 
$ streamlit hello
 
</source>
 
  
- 사용통계 출력시 아래 위치 옵션 변경
+
=== 코드 ===
<source lang=python>
 
~/.streamlit/config.toml, creating that file if necessary:
 
 
 
[browser]
 
gatherUsageStats = false
 
</source>
 
 
 
 
 
* github repository: https://github.com/streamlit/streamlit
 
* document: https://docs.streamlit.io/
 
* tutorial: https://docs.streamlit.io/en/stable/getting_started.html
 
 
 
 
 
 
== 실행 방법 ==
 
<source lang=python>
 
streamlit run test.py
 
</source>
 
 
 
* Local URL: http://localhost:8501
 
* Network URL: http://192.168.35.186:8501
 
 
 
 
 
== Streamlit 샘플 ==
 
* 샘플 소스
 
<source lang=python>
 
import streamlit as st
 
st.title('Hello Streamlit')
 
</source>
 
 
 
* 실행
 
<source lang=python>
 
streamlit run app.py
 
</source>
 
 
 
== Streamlit 샘플2 ==
 
=== import 선언 ===
 
 
<source lang=python>
 
<source lang=python>
 
import streamlit as st
 
import streamlit as st
 +
import plotly.express as px
 
import pandas as pd
 
import pandas as pd
</source>
+
import os
 +
import warnings
 +
warnings.filterwarnings('ignore')
  
=== 타이틀 생성 ===
+
st.set_page_config(page_title="Superstore!!!", page_icon=":bar_chart:",layout="wide")
<source lang=python>
 
st.title('My first app')
 
  
st.write("Here's our first attempt at using data to create a table:")
+
st.title(" :bar_chart: Sample SuperStore EDA")
 +
st.markdown('<style>div.block-container{padding-top:1rem;}</style>',unsafe_allow_html=True)
  
st.write(pd.DataFrame({
+
fl = st.file_uploader(":file_folder: Upload a file",type=(["csv","txt","xlsx","xls"]))
    'first column': [1, 2, 3, 4],
+
if fl is not None:
     'second column': [10, 20, 30, 40]
+
    filename = fl.name
}))
+
    st.write(filename)
 +
    df = pd.read_csv(filename, encoding = "ISO-8859-1")
 +
else:
 +
     os.chdir(r"C:\Users\AEPAC\Desktop\Streamlit")
 +
    df = pd.read_csv("Superstore.csv", encoding = "ISO-8859-1")
  
</source>
+
col1, col2 = st.columns((2))
* st.write()는 str 타입뿐만 아니라 pandas의 DataFrame 도 write 가능.
+
df["Order Date"] = pd.to_datetime(df["Order Date"])
 
=== 스트림릿 실행 ===
 
<source lang=python>
 
$ streamlit run first_app.py
 
</source>
 
 
 
== 문자열 관련 ==
 
<source lang=sql>
 
import streamlit as st
 
 
 
# 타이틀
 
st.title('this is title')
 
# 헤더
 
st.header('this is header')
 
# 서브헤더
 
st.subheader('this is subheader')
 
</source>
 
 
 
== 레이아웃 만들기 ==
 
* 레이아웃으로 웹페이지 분할
 
* columns 함수
 
  
<source lang=sql>
+
# Getting the min and max date
import streamlit as st
+
startDate = pd.to_datetime(df["Order Date"]).min()
 +
endDate = pd.to_datetime(df["Order Date"]).max()
  
col1,col2 = st.columns([2,3])
+
with col1:
# 공간을 2:3 으로 분할하여 col1과 col2 컬럼 생성. 
+
    date1 = pd.to_datetime(st.date_input("Start Date", startDate))
  
with col1 :
+
with col2:
  # column 1 에 담을 내용
+
    date2 = pd.to_datetime(st.date_input("End Date", endDate))
  st.title('here is column1')
 
with col2 :
 
  # column 2 에 담을 내용
 
  st.title('here is column2')
 
  st.checkbox('this is checkbox1 in col2 ')
 
  
 +
df = df[(df["Order Date"] >= date1) & (df["Order Date"] <= date2)].copy()
  
# with 구문 말고 다르게 사용 가능
+
st.sidebar.header("Choose your filter: ")
col1.subheader(' i am column1  subheader !! ')
+
# Create for Region
col2.checkbox('this is checkbox2 in col2 ')  
+
region = st.sidebar.multiselect("Pick your Region", df["Region"].unique())
# => 위에 with col2: 안의 내용과 같은 기능
+
if not region:
</source>
+
    df2 = df.copy()
 +
else:
 +
    df2 = df[df["Region"].isin(region)]
  
 +
# Create for State
 +
state = st.sidebar.multiselect("Pick the State", df2["State"].unique())
 +
if not state:
 +
    df3 = df2.copy()
 +
else:
 +
    df3 = df2[df2["State"].isin(state)]
  
== Data Visualization ==
+
# Create for City
=== line chart 그리기 ===
+
city = st.sidebar.multiselect("Pick the City",df3["City"].unique())
​* st.line_chart() 메서드로 line chart 추가
 
<source lang=python>
 
chart_data = pd.DataFrame(
 
    np.random.randn(20, 3),
 
    columns=['a', 'b', 'c'])
 
  
st.line_chart(chart_data)
+
# Filter the data based on Region, State and City
</source>
 
  
=== map 그리기 ===
+
if not region and not state and not city:
​* st.map() 메서드 사용.
+
    filtered_df = df
<source lang=python>
+
elif not state and not city:
map_data = pd.DataFrame(
+
    filtered_df = df[df["Region"].isin(region)]
     np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
+
elif not region and not city:
     columns=['lat', 'lon'])
+
    filtered_df = df[df["State"].isin(state)]
 +
elif state and city:
 +
    filtered_df = df3[df["State"].isin(state) & df3["City"].isin(city)]
 +
elif region and city:
 +
    filtered_df = df3[df["Region"].isin(region) & df3["City"].isin(city)]
 +
elif region and state:
 +
     filtered_df = df3[df["Region"].isin(region) & df3["State"].isin(state)]
 +
elif city:
 +
    filtered_df = df3[df3["City"].isin(city)]
 +
else:
 +
     filtered_df = df3[df3["Region"].isin(region) & df3["State"].isin(state) & df3["City"].isin(city)]
  
st.map(map_data)
+
category_df = filtered_df.groupby(by = ["Category"], as_index = False)["Sales"].sum()
</source>
 
  
=== Checkbox show/hide data ===
+
with col1:
​* st.checkbox() 이용, 체크박스를 이용해서 데이터 show/hide 설정.  
+
    st.subheader("Category wise Sales")
* st.checkbox()는 위젯명을 argument로 받아서 처리.
+
    fig = px.bar(category_df, x = "Category", y = "Sales", text = ['${:,.2f}'.format(x) for x in category_df["Sales"]],
<source lang=python>
+
                template = "seaborn")
if st.checkbox('Show dataframe'):
+
     st.plotly_chart(fig,use_container_width=True, height = 200)
     chart_data = pd.DataFrame(
 
      np.random.randn(20, 3),
 
      columns=['a', 'b', 'c'])
 
  
     chart_data
+
with col2:
 +
     st.subheader("Region wise Sales")
 +
    fig = px.pie(filtered_df, values = "Sales", names = "Region", hole = 0.5)
 +
    fig.update_traces(text = filtered_df["Region"], textposition = "outside")
 +
    st.plotly_chart(fig,use_container_width=True)
  
</source>
+
cl1, cl2 = st.columns((2))
 +
with cl1:
 +
    with st.expander("Category_ViewData"):
 +
        st.write(category_df.style.background_gradient(cmap="Blues"))
 +
        csv = category_df.to_csv(index = False).encode('utf-8')
 +
        st.download_button("Download Data", data = csv, file_name = "Category.csv", mime = "text/csv",
 +
                            help = 'Click here to download the data as a CSV file')
  
+
with cl2:
+
    with st.expander("Region_ViewData"):
=== Selectbox ===  
+
        region = filtered_df.groupby(by = "Region", as_index = False)["Sales"].sum()
​* st.selectbox()는 pandas.Series를 입력으로 받아서 옵션 선택.
+
        st.write(region.style.background_gradient(cmap="Oranges"))
 +
        csv = region.to_csv(index = False).encode('utf-8')
 +
        st.download_button("Download Data", data = csv, file_name = "Region.csv", mime = "text/csv",
 +
                        help = 'Click here to download the data as a CSV file')
 +
       
 +
filtered_df["month_year"] = filtered_df["Order Date"].dt.to_period("M")
 +
st.subheader('Time Series Analysis')
  
<source lang=python>
+
linechart = pd.DataFrame(filtered_df.groupby(filtered_df["month_year"].dt.strftime("%Y : %b"))["Sales"].sum()).reset_index()
import streamlit as st
+
fig2 = px.line(linechart, x = "month_year", y="Sales", labels = {"Sales": "Amount"},height=500, width = 1000,template="gridon")
import pandas as pd
+
st.plotly_chart(fig2,use_container_width=True)
  
st.title('TUNiBerse')
+
with st.expander("View Data of TimeSeries:"):
option = st.selectbox(
+
    st.write(linechart.T.style.background_gradient(cmap="Blues"))
     '당신의 직책을 선택해주세요.',
+
     csv = linechart.to_csv(index=False).encode("utf-8")
    pd.Series(['CEO', 'AI Engineer', 'Intern', 'Product Manager']))
+
    st.download_button('Download Data', data = csv, file_name = "TimeSeries.csv", mime ='text/csv')
  
'You selected: ', option
+
# Create a treem based on Region, category, sub-Category
</source>
+
st.subheader("Hierarchical view of Sales using TreeMap")
+
fig3 = px.treemap(filtered_df, path = ["Region","Category","Sub-Category"], values = "Sales",hover_data = ["Sales"],
==== Selectbox를 사이드로 이동 ====
+
                  color = "Sub-Category")
<source lang=python>
+
fig3.update_layout(width = 800, height = 650)
import streamlit as st
+
st.plotly_chart(fig3, use_container_width=True)
import pandas as pd
 
  
st.title('TUNiBerse')
+
chart1, chart2 = st.columns((2))
option = st.sidebar.selectbox(
+
with chart1:
     '당신의 직책을 선택해주세요.',
+
    st.subheader('Segment wise Sales')
    pd.Series(['CEO', 'AI Engineer', 'Intern', 'Product Manager']))
+
    fig = px.pie(filtered_df, values = "Sales", names = "Segment", template = "plotly_dark")
 +
     fig.update_traces(text = filtered_df["Segment"], textposition = "inside")
 +
    st.plotly_chart(fig,use_container_width=True)
  
'You selected: ', option
+
with chart2:
 +
    st.subheader('Category wise Sales')
 +
    fig = px.pie(filtered_df, values = "Sales", names = "Category", template = "gridon")
 +
    fig.update_traces(text = filtered_df["Category"], textposition = "inside")
 +
    st.plotly_chart(fig,use_container_width=True)
  
</source>
+
import plotly.figure_factory as ff
+
st.subheader(":point_right: Month wise Sub-Category Sales Summary")
* streamlit에서 제공하는 대부분의 element는 st.sidebar. [element_name]() 포맷으로 사용 가능.
+
with st.expander("Summary_Table"):
* 위의 위젯 외에도 button, expander 등 여러 위젯 사용 가능.
+
    df_sample = df[0:5][["Region","State","City","Category","Sales","Profit","Quantity"]]
+
    fig = ff.create_table(df_sample, colorscale = "Cividis")
=== progress 진행현황표시 ===
+
    st.plotly_chart(fig, use_container_width=True)
​* st.progress()이용, 웹이지에 진행현황을 표시.
 
<source lang=python>
 
import time
 
  
'Starting a long computation...'
+
    st.markdown("Month wise sub-Category Table")
 +
    filtered_df["month"] = filtered_df["Order Date"].dt.month_name()
 +
    sub_category_Year = pd.pivot_table(data = filtered_df, values = "Sales", index = ["Sub-Category"],columns = "month")
 +
    st.write(sub_category_Year.style.background_gradient(cmap="Blues"))
  
# Add a placeholder
+
# Create a scatter plot
latest_iteration = st.empty()
+
data1 = px.scatter(filtered_df, x = "Sales", y = "Profit", size = "Quantity")
bar = st.progress(0)
+
data1['layout'].update(title="Relationship between Sales and Profits using Scatter Plot.",
 +
                      titlefont = dict(size=20),xaxis = dict(title="Sales",titlefont=dict(size=19)),
 +
                      yaxis = dict(title = "Profit", titlefont = dict(size=19)))
 +
st.plotly_chart(data1,use_container_width=True)
  
for i in range(100):
+
with st.expander("View Data"):
  # Update the progress bar with each iteration.
+
    st.write(filtered_df.iloc[:500,1:20:2].style.background_gradient(cmap="Oranges"))
  latest_iteration.text(f'Iteration {i+1}')
 
  bar.progress(i + 1)
 
  time.sleep(0.1)
 
  
'...and now we\'re done!
+
# Download orginal DataSet
 +
csv = df.to_csv(index = False).encode('utf-8')
 +
st.download_button('Download Data', data = csv, file_name = "Data.csv",mime = "text/csv")
 
</source>
 
</source>
 
=== APP Deploy , Manage , Share ===
 
* streamlit으로 개발한 app은 Streamlit Cloud로 deploy, manage, share 가능.
 
* 현재 Streamlit Cloud는 초대를 받은 멤버에 한해서 사용이 가능합니다.
 
* Request an invite에 몇 가지 사항을 제출하고 사용.
 
 
==== 3스텝으로 구현 가능 ====
 
​1. Put your app in a public Github repo (and make sure it has a requirements.txt!)
 
2. Sign into share.streamlit.io
 
3. Click ‘Deploy an app’ and then paste in your GitHub URL
 
 
  
== 참조 사이트 ==
+
=== adidas 쇼핑몰 ===
 +
* https://github.com/AbhisheakSaraswat/PythonStreamlit/blob/main/Dashboard.py
 +
=== 참조 사이트 ===
 
   
 
   
 
https://docs.kanaries.net/topics/Streamlit/streamlit-dashboard
 
https://docs.kanaries.net/topics/Streamlit/streamlit-dashboard

2024년 8월 26일 (월) 18:18 기준 최신판

thumb_up 추천메뉴 바로가기


1 streamlit dashbaord 개발[편집]

1.1 코드[편집]

import streamlit as st
import plotly.express as px
import pandas as pd
import os
import warnings
warnings.filterwarnings('ignore')

st.set_page_config(page_title="Superstore!!!", page_icon=":bar_chart:",layout="wide")

st.title(" :bar_chart: Sample SuperStore EDA")
st.markdown('<style>div.block-container{padding-top:1rem;}</style>',unsafe_allow_html=True)

fl = st.file_uploader(":file_folder: Upload a file",type=(["csv","txt","xlsx","xls"]))
if fl is not None:
    filename = fl.name
    st.write(filename)
    df = pd.read_csv(filename, encoding = "ISO-8859-1")
else:
    os.chdir(r"C:\Users\AEPAC\Desktop\Streamlit")
    df = pd.read_csv("Superstore.csv", encoding = "ISO-8859-1")

col1, col2 = st.columns((2))
df["Order Date"] = pd.to_datetime(df["Order Date"])

# Getting the min and max date 
startDate = pd.to_datetime(df["Order Date"]).min()
endDate = pd.to_datetime(df["Order Date"]).max()

with col1:
    date1 = pd.to_datetime(st.date_input("Start Date", startDate))

with col2:
    date2 = pd.to_datetime(st.date_input("End Date", endDate))

df = df[(df["Order Date"] >= date1) & (df["Order Date"] <= date2)].copy()

st.sidebar.header("Choose your filter: ")
# Create for Region
region = st.sidebar.multiselect("Pick your Region", df["Region"].unique())
if not region:
    df2 = df.copy()
else:
    df2 = df[df["Region"].isin(region)]

# Create for State
state = st.sidebar.multiselect("Pick the State", df2["State"].unique())
if not state:
    df3 = df2.copy()
else:
    df3 = df2[df2["State"].isin(state)]

# Create for City
city = st.sidebar.multiselect("Pick the City",df3["City"].unique())

# Filter the data based on Region, State and City

if not region and not state and not city:
    filtered_df = df
elif not state and not city:
    filtered_df = df[df["Region"].isin(region)]
elif not region and not city:
    filtered_df = df[df["State"].isin(state)]
elif state and city:
    filtered_df = df3[df["State"].isin(state) & df3["City"].isin(city)]
elif region and city:
    filtered_df = df3[df["Region"].isin(region) & df3["City"].isin(city)]
elif region and state:
    filtered_df = df3[df["Region"].isin(region) & df3["State"].isin(state)]
elif city:
    filtered_df = df3[df3["City"].isin(city)]
else:
    filtered_df = df3[df3["Region"].isin(region) & df3["State"].isin(state) & df3["City"].isin(city)]

category_df = filtered_df.groupby(by = ["Category"], as_index = False)["Sales"].sum()

with col1:
    st.subheader("Category wise Sales")
    fig = px.bar(category_df, x = "Category", y = "Sales", text = ['${:,.2f}'.format(x) for x in category_df["Sales"]],
                 template = "seaborn")
    st.plotly_chart(fig,use_container_width=True, height = 200)

with col2:
    st.subheader("Region wise Sales")
    fig = px.pie(filtered_df, values = "Sales", names = "Region", hole = 0.5)
    fig.update_traces(text = filtered_df["Region"], textposition = "outside")
    st.plotly_chart(fig,use_container_width=True)

cl1, cl2 = st.columns((2))
with cl1:
    with st.expander("Category_ViewData"):
        st.write(category_df.style.background_gradient(cmap="Blues"))
        csv = category_df.to_csv(index = False).encode('utf-8')
        st.download_button("Download Data", data = csv, file_name = "Category.csv", mime = "text/csv",
                            help = 'Click here to download the data as a CSV file')

with cl2:
    with st.expander("Region_ViewData"):
        region = filtered_df.groupby(by = "Region", as_index = False)["Sales"].sum()
        st.write(region.style.background_gradient(cmap="Oranges"))
        csv = region.to_csv(index = False).encode('utf-8')
        st.download_button("Download Data", data = csv, file_name = "Region.csv", mime = "text/csv",
                        help = 'Click here to download the data as a CSV file')
        
filtered_df["month_year"] = filtered_df["Order Date"].dt.to_period("M")
st.subheader('Time Series Analysis')

linechart = pd.DataFrame(filtered_df.groupby(filtered_df["month_year"].dt.strftime("%Y : %b"))["Sales"].sum()).reset_index()
fig2 = px.line(linechart, x = "month_year", y="Sales", labels = {"Sales": "Amount"},height=500, width = 1000,template="gridon")
st.plotly_chart(fig2,use_container_width=True)

with st.expander("View Data of TimeSeries:"):
    st.write(linechart.T.style.background_gradient(cmap="Blues"))
    csv = linechart.to_csv(index=False).encode("utf-8")
    st.download_button('Download Data', data = csv, file_name = "TimeSeries.csv", mime ='text/csv')

# Create a treem based on Region, category, sub-Category
st.subheader("Hierarchical view of Sales using TreeMap")
fig3 = px.treemap(filtered_df, path = ["Region","Category","Sub-Category"], values = "Sales",hover_data = ["Sales"],
                  color = "Sub-Category")
fig3.update_layout(width = 800, height = 650)
st.plotly_chart(fig3, use_container_width=True)

chart1, chart2 = st.columns((2))
with chart1:
    st.subheader('Segment wise Sales')
    fig = px.pie(filtered_df, values = "Sales", names = "Segment", template = "plotly_dark")
    fig.update_traces(text = filtered_df["Segment"], textposition = "inside")
    st.plotly_chart(fig,use_container_width=True)

with chart2:
    st.subheader('Category wise Sales')
    fig = px.pie(filtered_df, values = "Sales", names = "Category", template = "gridon")
    fig.update_traces(text = filtered_df["Category"], textposition = "inside")
    st.plotly_chart(fig,use_container_width=True)

import plotly.figure_factory as ff
st.subheader(":point_right: Month wise Sub-Category Sales Summary")
with st.expander("Summary_Table"):
    df_sample = df[0:5][["Region","State","City","Category","Sales","Profit","Quantity"]]
    fig = ff.create_table(df_sample, colorscale = "Cividis")
    st.plotly_chart(fig, use_container_width=True)

    st.markdown("Month wise sub-Category Table")
    filtered_df["month"] = filtered_df["Order Date"].dt.month_name()
    sub_category_Year = pd.pivot_table(data = filtered_df, values = "Sales", index = ["Sub-Category"],columns = "month")
    st.write(sub_category_Year.style.background_gradient(cmap="Blues"))

# Create a scatter plot
data1 = px.scatter(filtered_df, x = "Sales", y = "Profit", size = "Quantity")
data1['layout'].update(title="Relationship between Sales and Profits using Scatter Plot.",
                       titlefont = dict(size=20),xaxis = dict(title="Sales",titlefont=dict(size=19)),
                       yaxis = dict(title = "Profit", titlefont = dict(size=19)))
st.plotly_chart(data1,use_container_width=True)

with st.expander("View Data"):
    st.write(filtered_df.iloc[:500,1:20:2].style.background_gradient(cmap="Oranges"))

# Download orginal DataSet
csv = df.to_csv(index = False).encode('utf-8')
st.download_button('Download Data', data = csv, file_name = "Data.csv",mime = "text/csv")