首页 > 编程语言 >【小沐学Python】Python实现Web图表功能(Dash之基本功能)

【小沐学Python】Python实现Web图表功能(Dash之基本功能)

时间:2023-11-04 12:35:31浏览次数:34  
标签:__ Web dash Python app Dash 小沐学 html import

1、简介

Dash是下载量最大,最值得信赖的Python框架,用于构建ML和数据科学Web应用程序。

Dash是一个用来创建 web 应用的 python 库,它建立在 Plotly.js(同一个团队开发)、React 和 Flask 之上,主要的用户群体是数据分析者、AI 从业者,可以帮助他们快速搭建非常美观的网页应用,而且不需要你懂 javascript。

2、功能示例

2.1 Hello World

下面的代码创建了一个非常小的“Hello World”Dash应用程序。

from dash import Dash, html

app = Dash(__name__)

app.layout = html.Div([
    html.Div(children='Hello World, 爱看书的小沐!')
])

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

在这里插入图片描述

2.2 连接到数据

向应用添加数据的方法有很多种:API、外部数据库、本地文件、JSON 文件等。 在此示例中,我们将重点介绍合并 CSV 工作表中数据的最常见方法之一。

from dash import Dash, html, dash_table
import pandas as pd

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

# Initialize the app
app = Dash(__name__)

# App layout
app.layout = html.Div([
    html.Div(children='My First App with Data'),
    dash_table.DataTable(data=df.to_dict('records'), page_size=10)
])

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

在这里插入图片描述

2.3 可视化数据

Plotly 图形库有 50 多种图表类型可供选择。 在此示例中,我们将使用直方图。

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

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

# Initialize the app
app = Dash(__name__)

# App layout
app.layout = html.Div([
    html.Div(children='My First App with Data and a Graph'),
    dash_table.DataTable(data=df.to_dict('records'), page_size=10),
    dcc.Graph(figure=px.histogram(df, x='continent', y='lifeExp', histfunc='avg'))
])

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

在这里插入图片描述

2.4 控件和回调

到目前为止,你已构建了一个显示表格数据和图形的静态应用。 但是,当您开发更复杂的Dash应用程序时,您可能希望为应用程序用户提供更多的自由来与应用程序交互并更深入地探索数据。 为此,需要使用回调函数向应用添加控件。

在此示例中,我们将向应用布局添加单选按钮。然后,我们将构建回调以创建单选按钮和直方图之间的交互。

from dash import Dash, html, dash_table, dcc, callback, Output, Input
import pandas as pd
import plotly.express as px

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

# Initialize the app
app = Dash(__name__)

# App layout
app.layout = html.Div([
    html.Div(children='My First App with Data, Graph, and Controls'),
    html.Hr(),
    dcc.RadioItems(options=['pop', 'lifeExp', 'gdpPercap'], value='lifeExp', id='controls-and-radio-item'),
    dash_table.DataTable(data=df.to_dict('records'), page_size=6),
    dcc.Graph(figure={}, id='controls-and-graph')
])

# Add controls to build the interaction
@callback(
    Output(component_id='controls-and-graph', component_property='figure'),
    Input(component_id='controls-and-radio-item', 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)

在这里插入图片描述

2.5 设置应用的样式

上一节中的示例使用Dash HTML组件来构建简单的应用程序布局,但您可以设置应用程序的样式以使其看起来更专业。

  • 本节将简要概述可用于增强达世币应用程序布局样式的多种工具:
    • HTML and CSS
    • Dash Design Kit (DDK)
    • Dash Bootstrap Components
    • Dash Mantine Components

2.5.1 HTML and CSS

HTML 和 CSS 是在 Web 上呈现内容的最低级别的界面。 HTML 是一组组件,CSS 是应用于这些组件的一组样式。 CSS 样式可以通过属性在组件中应用,也可以将它们定义为引用属性的单独 CSS 文件.

from dash import Dash, html, dash_table, dcc, callback, Output, Input
import pandas as pd
import plotly.express as px

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

# Initialize the app - incorporate css
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = Dash(__name__, external_stylesheets=external_stylesheets)

# App layout
app.layout = html.Div([
    html.Div(className='row', children='My First App with Data, Graph, and Controls',
             style={'textAlign': 'center', 'color': 'blue', 'fontSize': 30}),

    html.Div(className='row', children=[
        dcc.RadioItems(options=['pop', 'lifeExp', 'gdpPercap'],
                       value='lifeExp',
                       inline=True,
                       id='but1')
    ]),

    html.Div(className='row', children=[
        html.Div(className='six columns', children=[
            dash_table.DataTable(data=df.to_dict('records'), page_size=11, style_table={'overflowX': 'auto'})
        ]),
        html.Div(className='six columns', children=[
            dcc.Graph(figure={}, id='histo-chart-final')
        ])
    ])
])

# Add controls to build the interaction
@callback(
    Output(component_id='histo-chart-final', component_property='figure'),
    Input(component_id='but1', 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)

在这里插入图片描述

2.5.2 Dash Design Kit (DDK)

Dash 设计工具包是我们专为Dash 构建的高级UI框架。 使用Dash设计工具包,您无需使用HTML或CSS。默认情况下,应用程序是移动响应式的,并且一切都是主题化的。 <font color=red>请注意,如果没有Dash企业许可证,您将无法运行此示例。

from dash import Dash, html, dash_table, dcc, callback, Output, Input
import pandas as pd
import plotly.express as px
import dash_design_kit as ddk

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

# Initialize the app
app = Dash(__name__)

# App layout
app.layout = ddk.App([
    ddk.Header(ddk.Title('My First App with Data, Graph, and Controls')),
    dcc.RadioItems(options=['pop', 'lifeExp', 'gdpPercap'],
                    value='lifeExp',
                    inline=True,
                    id='my-ddk-radio-items-final'),
    ddk.Row([
        ddk.Card([
            dash_table.DataTable(data=df.to_dict('records'), page_size=12, style_table={'overflowX': 'auto'})
        ], width=50),
        ddk.Card([
            ddk.Graph(figure={}, id='graph-placeholder-ddk-final')
        ], width=50),
    ]),

])

# Add controls to build the interaction
@callback(
    Output(component_id='graph-placeholder-ddk-final', component_property='figure'),
    Input(component_id='my-ddk-radio-items-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)

2.5.3 Dash Bootstrap Components

Dash Bootstrap是一个基于引导组件系统构建的社区维护库。 虽然它没有被Plotly官方维护或支持,但Dash Bootstrap是构建优雅应用程序布局的强大方式。 请注意,我们首先定义一行,然后使用 and 组件定义行内列的宽度。

pip install dash-bootstrap-components
# 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)

在这里插入图片描述

2.5.4 Dash Mantine Components

Dash Mantine是一个社区维护的库,建立在Mantine组件系统之上。 虽然它没有得到Plotly团队的官方维护或支持,但Dash Mantine是另一种自定义应用程序布局的强大方式。 破折号组件使用网格模块来构建布局。

pip install dash-mantine-components

在这里插入图片描述

from dash import Dash, html, dash_table, dcc, callback, Output, Input
import pandas as pd
import plotly.express as px
import dash_mantine_components as dmc

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

# Initialize the app - incorporate a Dash Mantine theme
external_stylesheets = [dmc.theme.DEFAULT_COLORS]
app = Dash(__name__, external_stylesheets=external_stylesheets)

# App layout
app.layout = dmc.Container([
    dmc.Title('My First App with Data, Graph, and Controls', color="blue", size="h3"),
    dmc.RadioGroup(
            [dmc.Radio(i, value=i) for i in  ['pop', 'lifeExp', 'gdpPercap']],
            id='my-dmc-radio-item',
            value='lifeExp',
            size="sm"
        ),
    dmc.Grid([
        dmc.Col([
            dash_table.DataTable(data=df.to_dict('records'), page_size=12, style_table={'overflowX': 'auto'})
        ], span=6),
        dmc.Col([
            dcc.Graph(figure={}, id='graph-placeholder')
        ], span=6),
    ]),

], fluid=True)

# Add controls to build the interaction
@callback(
    Output(component_id='graph-placeholder', component_property='figure'),
    Input(component_id='my-dmc-radio-item', 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)

在这里插入图片描述

结语

如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;╮( ̄▽ ̄)╭ 如果您感觉方法或代码不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进;o_O??? 如果您需要相关功能的代码定制化开发,可以留言私信作者;(✿◡‿◡) 感谢各位大佬童鞋们的支持!( ´ ▽´ )ノ ( ´ ▽´)っ!!!

标签:__,Web,dash,Python,app,Dash,小沐学,html,import
From: https://blog.51cto.com/fish/8180698

相关文章

  • 在Anaconda中安装Python的seaborn库
      本文介绍在Anaconda的环境中,安装Python语言中,常用的一个绘图库seaborn模块的方法。  seaborn模块是基于Matplotlib的数据可视化库,它提供了一种更简单、更漂亮的界面来创建各种统计图形。seaborn模块主要用于数据探索、数据分析和数据可视化,使得我们在Python中创建各种统计图......
  • 基于Python+Pygame实现一个滑雪小游戏
    目录项目介绍Pygame介绍项目文件夹介绍演示视频代码免费领取一、项目介绍使用介绍:运行main.py文件后,通过左右按键可以控制小人的移动,如果经过旗杆那么+10分,如果碰到树木那么减50分。二、Pygame介绍Pygame是一个用于游戏开发和多媒体应用的Python库。它是基于SDL(Simple......
  • 【Web】https 与 http 的区别
    一、基本概念http:超文本传输协议,一种网络传输协议,一个客户端和服务器请求和应答的标准(TCP)。https:简单讲就是在http基础上使用SSL或TLS对请求和响应进行加密,建立一个信息安全通道。https工作原理:客户端使用httpsurl访问服务器,要求与web服务器建立ssl连接web服务器......
  • Python脚本学习——文件处理
    一、模糊查找文件importospath=r"F:\Typora"files=os.listdir(path)foriinfiles:#查找文件中含有某个字符串的文件并确定文件类型(也就是后缀)if'Typora'iniandi.endswith('.exe'):print(i)二、文件自动归类注意当使用的是绝对路径时,需要对文件......
  • python毕业设计选题15例,马上要毕业啦,大家做好准备了没
    Hi,大家好,大四的同学马上要开始毕业设计啦,大家做好准备了没!学长给大家详细整理了最新的python计算机毕设相关选题,对选题有任何疑问,都可以问学长哦.1.网上商城系统这是一个基于python+vue开发的商城网站,模仿京东购物模式,平台采用B/S结构,后端采用主流的Python语言进行开发,前端......
  • python 字符串格式化
    Python字符串的格式化分为两种:1)%方式  2)str.format() 方式。str.format()是比%较新的方式,大多数的Python代码仍然使用%操作符。但最终会被str.format()代替,推荐使用str.format()==============================================================================......
  • python——基础学习篇(3)
    【列表的加法和乘法】加法:s=[1,2,3], t=[4,5,6,], s+t=[1,2,3,4,5,6]乘法:s×3=重复三次【嵌套列表(二维列表)】matrix=[]直接应用访问嵌套循环(可用循环):is (同一性运算符)——字符串不变,列表可变 copy:y=x.copy() ——列表的一个copy方法,  y=copy.copy(列表,字......
  • python——基础学习篇(6)
    【字典】关键符号:{} 创建字典:1.直接使用大括号冒号的方法 2. 使用dict函数使用列表作用元素,每个元素又用元组包裹增:fromkeys(iterable[,  values]) :suchas:——d=dict.fromkeys("fish",250)——{“f”:250,“i”:250,“s”:250 ,“h”:250......
  • python——基础学习篇(5)
    【拆分和拼接】partition(从左往右找分割符)——rpartition(从右往左)split(sep=none,maxsplit=-1)——可把分割为一个一个·jion(iterable)——尽量用jion少用加法【格式化字符串的方法】format使用{}替换字段align:"<"左对齐(默认)   “>” 右对齐 ......
  • python——基础学习篇(4)
    【字符串】大小写字母换来换去:capitalize:首字母大写(其他小写)                   casefold:返回所有的字母都是小写的字符串                   title:字符串每个单词的首字母变成大写单词其他字......