【Dash】HTML 组件创建直方图

一、HTML Component

Dash HTML Components contains a component class for every HTML tag as well as keyword arguments for all of the HTML arguments.

from dash import Dash, dcc, html
import plotly.express as px
import pandas as pd

app = Dash()

colors = {
    'background': '#293844',
    'text': '#F2F2F2'
}

df = pd.DataFrame({
    'Fruit': ['Apples', 'Oranges', 'Bananas', 'Apples', 'Oranges', 'Bananas'],
    'Amount': [4, 1, 4, 4, 2, 5],
    'City': ['SF', 'SF', 'SF', 'Montreal', 'Montreal', 'Montreal']
})

fig = px.bar(df, x='Fruit', y='Amount', color='City', barmode='group',
             color_discrete_sequence=['#FFCCCC', '#FFF1DD', '#99C3D9', '#89D7BC'])

fig.update_layout(
    plot_bgcolor=colors['background'],
    paper_bgcolor=colors['background'],
    font_color=colors['text']
)

app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[
    html.H1(
        children='Hello Dash',
        style={
            'textAlign': 'center',
            'color': colors['text']
        }
    ),

    html.Div(children='Dash: A web application framework for your data.', style={
        'textAlign': 'center',
        'color': colors['text']
    }),

    dcc.Graph(
        id='example-graph-2',
        figure=fig
    )
])


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


二、解读

from dash import Dash, dcc, html
import plotly.express as px
import pandas as pd
  • 导入Dash类(创建应用程序)、dcc组件(动态交互组件)、html组件(静态HTML组件)
  • 导入 plotly.express 模块,用于创建 Plotly 图表
  • 导入 pandas 库,用于数据处理
app = Dash()
  • 创建 Dash 类的实例,作为整个 Dash 应用程序的入口点
colors = {
    'background': '#293844',
    'text': '#F2F2F2'
}
  • 定义一个字典 colors ,包含两个键值对,分别设置背景颜色和文本颜色
df = pd.DataFrame({
    'Fruit': ['Apples', 'Oranges', 'Bananas', 'Apples', 'Oranges', 'Bananas'],
    'Amount': [4, 1, 4, 4, 2, 5],
    'City': ['SF', 'SF', 'SF', 'Montreal', 'Montreal', 'Montreal']
})
  • 创建一个名为 dfpandas DataFrame,其中包含三列:'Fruit'、'Amount' 和 'City'。它用于存储水果数据。
FruitAmountCity
Apples4SF
Oranges1SF
Bananas4SF
Apples4Montreal
Oranges2Montreal
Bananas5Montreal

fig = px.bar(df, x='Fruit', y='Amount', color='City', barmode='group',
            color_discrete_sequence=['#FFCCCC', '#FFF1DD', '#99C3D9', '#89D7BC'])
  • px.bar 创建一个柱形图
  • df:数据源
  • x 参数:指定 x 轴为 'Fruit'
  • y 参数:指定 y 轴为 'Amount'
  • color 参数:按 'City' 列对条形进行分组
  • barmode 参数:控制柱形图显示方式:
    • ='group' :每个分组的条形并排显示
    • ='overlay':每个分组的条形重叠显示
    • ='stack':每个分组的条形堆叠显示
  • color_discrete_sequence 定义不同城市的条形颜色。
fig.update_layout(
    plot_bgcolor=colors['background'],
    paper_bgcolor=colors['background'],
    font_color=colors['text']
)
  • update_layout 方法更新图表的布局设置,包括背景颜色、字体颜色、标题等,但不直接用于对条形图中的每个条形设置不同的颜色。
app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[
    html.H1(
        children='Hello Dash',
        style={
            'textAlign': 'center',
            'color': colors['text']
        }),

    html.Div(children='Dash: A web application framework for your data.', 
        style={
            'textAlign': 'center',
            'color': colors['text']
        }),


    dcc.Graph(
        id='example-graph-2',
        figure=fig
    )
])
  • app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[...]

        设置 app 布局,用 html.Div 组件包裹所有子组件,并设置背景颜色。

        children是一个列表,包含所有要显示的子组件。

  • html.H1(children=...., style={...})

        创建一个标题组件 html.H1,显示 Hello Dash,文本居中,并定义文本颜色

  • html.Div(children=..., style={...}) 

        创建一个 html.Div 组件,文本居中,并定义文本颜色

  • dcc.Graph(id='example-graph-2', figure=fig)

        创建一个 dcc.Graph 组件,用于显示之前创建的图表 fig。

        id 参数用于标识这个图表,以便在应用程序中引用。

  

  • 12
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Dash 是一个用于构建 Web 应用程序的 Python 框架,它提供了丰富的 UI 组件,方便用户快速构建交互式的 Web 应用程序。其中之一就是 Dash 的菜单组件,可以帮助用户轻松地构建具有导航功能的 Web 应用程序。下面是一个简单的 Dash 菜单组件实现的示例。 ```python import dash import dash_core_components as dcc import dash_html_components as html app = dash.Dash(__name__) app.layout = html.Div([ dcc.Location(id='url', refresh=False), html.Div([ html.H2('Dash Menu'), html.Ul([ html.Li(html.A('Home', href='/')), html.Li(html.A('Page 1', href='/page-1')), html.Li(html.A('Page 2', href='/page-2')), ], className='nav') ], className='topnav'), html.Div(id='page-content') ]) @app.callback(dash.dependencies.Output('page-content', 'children'), [dash.dependencies.Input('url', 'pathname')]) def display_page(pathname): if pathname == '/': return html.Div([ html.H3('Home Page'), html.P('Welcome to the home page!') ]) elif pathname == '/page-1': return html.Div([ html.H3('Page 1'), html.P('Welcome to page 1!') ]) elif pathname == '/page-2': return html.Div([ html.H3('Page 2'), html.P('Welcome to page 2!') ]) else: return html.Div([ html.H4('Page not found'), html.P('Sorry, we could not find the page you were looking for.') ]) if __name__ == '__main__': app.run_server(debug=True) ``` 在这个例子中,我们使用 `dash_core_components` 和 `dash_html_components` 来构建 Dash 应用程序的 UI。我们首先创建了一个顶部导航菜单栏,其中包含三个导航链接:Home、Page 1 和 Page 2。然后,我们使用 `dcc.Location` 组件来监听 URL 的变化,并使用 `app.callback` 装饰器来更新页面内容。 在回调函数中,我们检查 URL 的路径名,并根据不同的路径名返回不同的页面内容。如果路径名是 `/`,则返回主页的内容;如果路径名是 `/page-1`,则返回页面 1 的内容;如果路径名是 `/page-2`,则返回页面 2 的内容。如果路径名不匹配任何页面,则返回一个“页面未找到”的错误消息。 通过这个例子,你可以看到 Dash 菜单组件的实现方式,以及如何使用回调函数更新页面内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值