【Dash】使用 Bootstrap Componnet 创建图表

一、Styling Your App

The examples in the previous section used Dash HTML Components to build a simple app layout, but you can style your app to look more professional. This section will give a brief overview of the multiple tools that you can use to enhance the layout style of a Dash app:

  • HTML and CSS
  • Dash Design kit (DDK)
  • Dash Bootstrap Components
  • Dash Mantine Components

二、Dash Bootstrap Components

Dash Bootstrap is a community-maintained library built off of the bootstrap component system. Although it is not officially maintained or supported by Plotly, Dash Bootstrap is a powerful way of building elegant app layouts. Notice that we first define a row and then the width of columns inside the row, using thedbc.Row and dbc.Colcomponents.

For the app below to run successfully, make sure to install the Dash Bootstrap Components library: pip install dash-bootstrap-components.

python 复制代码
# Import packages
from dash import Dash, html, dash_table, dcc, callback, Output, Input
import pandas as pd
import plotly.express as px
import dash_bootstrap_components as dbc

# Incorporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')

# Initialize the app - incorporate a Dash Bootstrap theme
external_stylesheets = [dbc.themes.CERULEAN]
app = Dash(__name__, external_stylesheets=external_stylesheets)

# App layout
app.layout = dbc.Container([
    dbc.Row([
        html.Div('My First App with Data, Graph, and Controls', className='text-primary text-center fs-3')
    ]),
    dbc.Row([
        dbc.RadioItems(options=[{'label': x, 'value': x} for x in ['pop', 'lifeExp', 'gdpPercap']],
                       value='lifeExp',
                       inline=True,
                       id='radio-buttons-final')
    ]),
    dbc.Row([
        dbc.Col([
            dash_table.DataTable(data=df.to_dict('records'), page_size=12, style_table={'overflowX': 'auto'})
        ], width=6),
        dbc.Col([
            dcc.Graph(figure={}, id='my-first-graph-final')
        ], width=6),
    ]),
], fluid=True)

# Add controls to build the interaction
@callback(
    Output(component_id='my-first-graph-final', component_property='figure'),
    Input(component_id='radio-buttons-final', component_property='value')
)
def update_graph(col_chosen):
    fig = px.histogram(df, x='continent', y=col_chosen, histfunc='avg')
    return fig


# Run the app
if __name__ == '__main__':
    app.run(debug=True)

三、解读

Dash Bootstrap Components 是 Dash 的一个拓展包,提供了一组预定义的 Bootstrap 样式组件。

python 复制代码
# Import packages
from dash import Dash, html, dash_table, dcc, callback, Output, Input
import pandas as pd
import plotly.express as px
import dash_bootstrap_components as dbc
  • 导入Python 库。Dash 用于创建 Web 应用,pandas 用于数据处理,plotly.express 用于创建图表,dash_bootstrap_component 用于提供 Bootstrap 样式的组件。
python 复制代码
# Incoporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')
  • 使用 pandas 的 read_csv 函数从URL 数据文件中加载数据到 DataFrame df。
python 复制代码
# Initialize the app - incorporate a Dash Bootstrap theme
external_stylesheets = [dbc.theme.CERULEAN]
app = Dash(__name__, external_stylesheets=external_stylesheets)
  • 初始化 Dash 应用并设置外部样式表,这里使用了 Dash Bootstrap Component 的 CERULEAN 主题(天蓝色主题)
python 复制代码
# App layout
app.layout = dbc.Container([
        #...
], fluid=True)
  • 定义应用的布局,使用 dbc.Container 作为根容器
  • fluid=True 使容器宽度自适应屏幕宽度。
python 复制代码
dbc.Row([
    html.Div('My First App with Data, Graph, and Controls', className='text-primary text-center fs-3')
]),
  • 创建一个 dbc.Row 容器,包含一个 html.Div 组件,显示应用的标题。
python 复制代码
dbc.Row([
    dbc.RadioItems(options=[{'label': x, 'value': x} for x in ['pop', 'lifeExp', 'gdpPercap']], value='lifeExp', inline=True, id='radio-buttons-final')
]),
  • 创建一个 dbc.Row 容器,包含 dbc.RadioItems 组件,用于创建一组单选按钮,选项为['pop', 'lifeExp', 'gdpPercap']。
python 复制代码
dbc.Row([
    dbc.Col([
        dash_table.DataTable(data=df.to_dict('records'), page_size=12, style_table={'overflowX': 'auto'})
        ], width=6),
    dbc.Col([
        dcc.Graph(figure={}, id='my-first-graph-final')
    ], width=6),
]),
  • 创建一个 dbc.Row 容器,包含两个 dbc.Col 组件,分别占据 6 列宽度。
  • 第一个 dbc.Col 包含 dash_table.DataTable 组件,用于显示数据表
  • 第二个 dbc.Col 包含 dcc.Graph 组件,用于显示图表
python 复制代码
@callback(
    Output(component_id='my-first-graph-final', component_property='figure'),
    Input(component_id='radio-buttons-final', component_property='value')
)
def update_graph(col_chosen):
    fig = px.histogram(df, x='continent', y=col_chosen, histfunc='avg')
    return fig
)
  • 定义一个回调函数 update_graph,它根据 dbc.RadioItems 组件的选中值动态更新 dcc.Graph 组件的图表。
  • 在回调函数内部,使用 plotly.express 的 px.histogram 创建一个直方图。
  • 从回调函数返回图表对象 fig,Dash 将使用这个对象更新图表组件。
相关推荐
2301_8050545615 分钟前
Python训练营打卡Day59(2025.7.3)
开发语言·python
lsx20240638 分钟前
CSS 网页布局:从基础到进阶
开发语言
万千思绪40 分钟前
【PyCharm 2025.1.2配置debug】
ide·python·pycharm
蜗牛沐雨43 分钟前
警惕 Rust 字符串的性能陷阱:`chars().nth()` 的深坑与高效之道
开发语言·后端·rust
2401_858286111 小时前
125.【C语言】数据结构之归并排序递归解法
c语言·开发语言·数据结构·算法·排序算法·归并排序
guygg882 小时前
基于matlab的FIR滤波器
开发语言·算法·matlab
双叶8362 小时前
(C++)学生管理系统(正式版)(map数组的应用)(string应用)(引用)(文件储存的应用)(C++教学)(C++项目)
c语言·开发语言·数据结构·c++
微风粼粼2 小时前
程序员在线接单
java·jvm·后端·python·eclipse·tomcat·dubbo
源代码•宸2 小时前
C++高频知识点(二)
开发语言·c++·经验分享
云天徽上2 小时前
【PaddleOCR】OCR表格识别数据集介绍,包含PubTabNet、好未来表格识别、WTW中文场景表格等数据,持续更新中......
python·ocr·文字识别·表格识别·paddleocr·pp-ocrv5