创建交互式可视化仪表板能增强数据洞察的展示效果,以下是4种实用的Python工具包及其使用方法:
1. Ipywidgets(Widgets)- 简介:Ipywidgets是一个代码简单直观的交互式包,为Jupyter Notebooks中的GUI提供HTML架构,可直接在Jupyter Notebook单元中创建交互式仪表板。
- 安装:pip install ipywidgets
- 启用:在命令提示符中运行以下代码:jupyter nbextension enable --py widgetsnbextension
- 示例:使用泰坦尼克号样本数据创建交互式仪表板,展示按类别变量分组的票价平均值。import seaborn as snsfrom ipywidgets import interacttitanic = sns.load_dataset('titanic')@interactdef create_fare_plot(col = titanic.drop(['fare', 'age'], axis =1).columns): sns.barplot(data = titanic, x = col, y ='fare')
2. Voila- 简介:Voila-dashboards是一个简单的Python包,能将Jupyter Notebook变成漂亮的Web仪表板。
- 安装:pip install voila
- 使用:安装完成后,刷新Jupyter Notebook,在notebook选项卡中找到新的Voila按钮,点击即可自动生成Voila仪表板。
3. Dash by Plotly- 简介:Dash是一个开源Python包,是基于Plotly可视化的低代码框架包。
- 安装:pip install dash
- 示例:创建一个简单的泰坦尼克号仪表板,展示票价与年龄的散点图,并添加回调交互。import dashfrom dash import dcc, html, Input, Outputimport plotly.express as pximport seaborn as snsapp = dash.Dash()df = sns.load_dataset('titanic')fig = px.scatter(df, x="fare", y="age", size="pclass", color="alive", hover_name="embark_town", log_x=True, size_max=60)app.layout = html.Div(children = [ html.H1(children='Titanic Dashboard'), dcc.Graph(id="fare_vs_age", figure=fig), html.H4("Change the value in the text box to see callbacks in action"), html.Div(["Input: ", dcc.Input(id='my-input', value='initial value', type='text')]), html.Br(), html.Div(id='my-output'),])@app.callback( Output(component_id='my-output', component_property='children'), Input(component_id='my-input', component_property='value'))def update_output_div(input_value): return f'Output: {input_value}'if __name__ == "__main__": app.run_server(debug=True)
4. Streamlit- 简介:Streamlit是一个开源Python包,旨在为数据科学家和机器学习项目创建Web应用程序,提供的API易于初学者使用。
- 安装:pip install streamlit
- 示例:创建一个泰坦尼克号仪表板,展示数据集、数值统计以及按生存情况分类的数值和类别特征可视化。import streamlit as stimport pandas as pdimport plotly.express as pximport seaborn as snsdf = sns.load_dataset('titanic')st.title('Titanic Dashboard')st.subheader('Dataset')st.dataframe(df)st.subheader('Data Numerical Statistic')st.dataframe(df.describe())st.subheader('Data Visualization with respect to Survived')left_column, right_column = st.columns(2)with left_column: 'Numerical Plot' num_feat = st.selectbox('Select Numerical Feature', df.select_dtypes('number').columns) fig = px.histogram(df, x = num_feat, color = 'survived') st.plotly_chart(fig, use_container_width=True)with right_column: 'Categorical column' cat_feat = st.selectbox('Select Categorical Feature', df.select_dtypes(exclude = 'number').columns) fig = px.histogram(df, x =cat_feat, color = 'survived' ) st.plotly_chart(fig, use_container_width=True)运行代码:streamlit run titanic_st.py
结论交互式仪表板能显著改善用户体验,在展示数据科学项目时值得推荐使用。上述4种工具包各有特点,可根据项目需求和个人偏好选择合适的工具。