時間:2023-07-05 18:30:02 | 來源:網(wǎng)站運營
時間:2023-07-05 18:30:02 來源:網(wǎng)站運營
Python 如何制作 Web 可視化頁面?:一談到Web頁面,可能大家首先想到就是HTML,CSS或JavaScript。# 安裝streamlitpip install streamlit -i https://mirror.baidu.com/pypi/simple/# 安裝Plotly Expresspip install plotly_express==0.4.0 -i https://mirror.baidu.com/pypi/simple/# 安裝xlrdpip install xlrd==1.2.0 -i https://mirror.baidu.com/pypi/simple/
因為我們的數(shù)據(jù)文件是xlsx格式,最新版的xlrd,只支持xls文件。# 命令行終端打開文件所在路徑cd Excel_Webapp# 運行網(wǎng)頁streamlit run app.py
成功以后會有提示,并且瀏覽器會自動彈出網(wǎng)頁。import pandas as pdimport streamlit as stimport plotly.express as pxfrom PIL import Image# 設(shè)置網(wǎng)頁名稱st.set_page_config(page_title='調(diào)查結(jié)果')# 設(shè)置網(wǎng)頁標(biāo)題st.header('2020年調(diào)查問卷')# 設(shè)置網(wǎng)頁子標(biāo)題st.subheader('2020年各部門對生產(chǎn)部的評分情況')
導(dǎo)入相關(guān)的Python包,pandas處理數(shù)據(jù),streamlit用來生成網(wǎng)頁,plotly.express則是生成圖表,PIL讀取圖片。# 讀取數(shù)據(jù)excel_file = '各部門對生產(chǎn)部的評分情況.xlsx'sheet_name = 'DATA'df = pd.read_excel(excel_file, sheet_name=sheet_name, usecols='B:D', header=3)# 此處為各部門參加問卷調(diào)查人數(shù)df_participants = pd.read_excel(excel_file, sheet_name=sheet_name, usecols='F:G', header=3)df_participants.dropna(inplace=True)# streamlit的多重選擇(選項數(shù)據(jù))department = df['部門'].unique().tolist()# streamlit的滑動條(年齡數(shù)據(jù))ages = df['年齡'].unique().tolist()
讀取Excel表格數(shù)據(jù),并且得出年齡分布以及部門情況,一共是有5個部門。# 滑動條, 最大值、最小值、區(qū)間值age_selection = st.slider('年齡:', min_value=min(ages), max_value=max(ages), value=(min(ages), max(ages)))# 多重選擇, 默認(rèn)全選department_selection = st.multiselect('部門:', department, default=department)
結(jié)果如下。# 根據(jù)選擇過濾數(shù)據(jù)mask = (df['年齡'].between(*age_selection)) & (df['部門'].isin(department_selection))number_of_result = df[mask].shape[0]# 根據(jù)篩選條件, 得到有效數(shù)據(jù)st.markdown(f'*有效數(shù)據(jù): {number_of_result}*')# 根據(jù)選擇分組數(shù)據(jù)df_grouped = df[mask].groupby(by=['評分']).count()[['年齡']]df_grouped = df_grouped.rename(columns={'年齡': '計數(shù)'})df_grouped = df_grouped.reset_index()
得到數(shù)據(jù)便可以繪制柱狀圖了。# 繪制柱狀圖, 配置相關(guān)參數(shù)bar_chart = px.bar(df_grouped, x='評分', y='計數(shù)', text='計數(shù)', color_discrete_sequence=['#F63366']*len(df_grouped), template='plotly_white')st.plotly_chart(bar_chart)
使用plotly繪制柱狀圖。# 添加圖片和交互式表格col1, col2 = st.beta_columns(2)image = Image.open('survey.jpg')col1.image(image, caption='Designed by 小F / 法納斯特', use_column_width=True)col2.dataframe(df[mask], width=300)
得到結(jié)果如下。# 繪制餅圖pie_chart = px.pie(df_participants, title='總的參加人數(shù)', values='人數(shù)', names='公司部門')st.plotly_chart(pie_chart)
結(jié)果如下。關(guān)鍵詞:
微信公眾號
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。