如何在单个浏览器页面上将多个图形添加到Dash应用程序? [英] How to add multiple graphs to Dash app on a single browser page?

查看:226
本文介绍了如何在单个浏览器页面上将多个图形添加到Dash应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我布局布局的方式是嵌套 html.Div 组件.对于每个图形以及相应的标题,文本等,我们创建另一个 html.Div ,在我们的应用程序中创建一个新的行".

要记住的一件事是,不同的组件需要唯一的ID .在此示例中,相同的图形显示了两次,但它们并非完全相同的对象.我们使用相同的plotly.express图形

制作两个 dcc.Graph 对象

我为您提供了另一个示例,其中我添加了另一个动态图.每当从下拉菜单中选择新的色标时,第二个图形就会更新.这是达世币真正的潜力所在.您可以在

您的下一个问题可能是,我如何并排放置多个图形?这是CSS和样式表很重要的地方.

您已经添加了外部样式表 https://codepen.io/chriddyp/pen/bWLwgP.css ,这使我们能够使用 className div的组成部分.

无论屏幕大小如何,网页的宽度均设置为12列.因此,如果我们要并排放置两个图形,每个图形要占据屏幕的50%,则每个图形都需要填充6列.

我们可以通过嵌套另一个 html.Div 作为上半行来实现.在上一个div中,我们可以再有两个div,根据类名六列指定样式.这样会将第一行分为两半

 导入破折号导入dash_core_components作为dcc将dash_html_components导入为html从dash.dependencies导入输入,输出将熊猫作为pd导入导入plotly.express为px从jupyter_dash导入JupyterDashexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']app =破折号(__name__,external_stylesheets = external_stylesheets)#假设您有一个长格式"数据框#有关更多选项,请参见https://plotly.com/python/px-arguments/df_bar = pd.DataFrame({水果":[苹果",橙子",香蕉",苹果",橙子",香蕉"],金额":[4、1、2、2、4、5],城市":["SF","SF","SF",蒙特利尔",蒙特利尔",蒙特利尔"]})图= px.bar(df_bar,x =水果",y =数量",颜色=城市",barmode =组")app.layout = html.Div(children = [#页面顶部的所有元素html.Div([html.Div([html.H1(children ='Hello Dash'),html.Div(children ='''Dash:适用于Python的Web应用程序框架.'''),dcc.Graph(id ='graph1',图=图),],className =六列"),html.Div([html.H1(children ='Hello Dash'),html.Div(children ='''Dash:适用于Python的Web应用程序框架.'''),dcc.Graph(id ='graph2',图=图),],className =六列"),],className ='row'),#页面的新行"中所有元素的新Divhtml.Div([html.H1(children ='Hello Dash'),html.Div(children ='''Dash:适用于Python的Web应用程序框架.'''),dcc.Graph(id ='graph3',图=图),],className ='row'),])如果__name__ =='__main__':app.run_server(debug = True) 

enter image description here

How do I add multiple graphs show in in picture on a same page? I am trying to add html.Div components to following code to update the page layout to add more graphs like that on single page, but these newly added graphs do not get shown on a page, only old graph is shown in picture is visible. What element should I modify, to let's say to add graph shown in uploaded image 3 times on single page of dash app on browser?


import dash
import dash_core_components as dcc
import dash_html_components as html
i[enter image description here][1]mport plotly.express as px
import pandas as pd

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df = pd.DataFrame({
    "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
    "Amount": [4, 1, 2, 2, 4, 5],
    "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})

fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    html.Div(children='''
        Dash: A web application framework for Python.
    '''),

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

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

解决方案

To add the same figure multiple times, you just need to extend your app.layout. I have extended you code below as an example.

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.express as px

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df_bar = pd.DataFrame({
    "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
    "Amount": [4, 1, 2, 2, 4, 5],
    "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})

fig = px.bar(df_bar, x="Fruit", y="Amount", color="City", barmode="group")

app.layout = html.Div(children=[
    # All elements from the top of the page
    html.Div([
        html.H1(children='Hello Dash'),

        html.Div(children='''
            Dash: A web application framework for Python.
        '''),

        dcc.Graph(
            id='graph1',
            figure=fig
        ),  
    ]),
    # New Div for all elements in the new 'row' of the page
    html.Div([
        html.H1(children='Hello Dash'),

        html.Div(children='''
            Dash: A web application framework for Python.
        '''),

        dcc.Graph(
            id='graph2',
            figure=fig
        ),  
    ]),
])

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

The way I have structured the layout is by nesting the html.Div components. For every figure and corresponding titles, text, etc. we make another html.Div that makes a new 'row' in our application.

The one thing to keep in mind is that different components need unique ids. In this example we have the same graph displayed twice, but they are not the exact same object. We are making two dcc.Graph objects using the same plotly.express figure

I have made another example for you where I have a added another figure that is dynamic. The second figure is updated every time a new colorscale is selected from the dropdown menu. This is were the real potential of Dash lies. You can read more about callback functions in this tutorial

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.express as px

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df_bar = pd.DataFrame({
    "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
    "Amount": [4, 1, 2, 2, 4, 5],
    "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})

fig = px.bar(df_bar, x="Fruit", y="Amount", color="City", barmode="group")

# Data for the tip-graph
df_tip = px.data.tips()

app.layout = html.Div(children=[
    # All elements from the top of the page
    html.Div([
        html.H1(children='Hello Dash'),

        html.Div(children='''
            Dash: A web application framework for Python.
        '''),

        dcc.Graph(
            id='example-graph',
            figure=fig
        ),  
    ]),
    # New Div for all elements in the new 'row' of the page
    html.Div([ 
        dcc.Graph(id='tip-graph'),
        html.Label([
            "colorscale",
            dcc.Dropdown(
                id='colorscale-dropdown', clearable=False,
                value='bluyl', options=[
                    {'label': c, 'value': c}
                    for c in px.colors.named_colorscales()
                ])
        ]),
    ])
])

# Callback function that automatically updates the tip-graph based on chosen colorscale
@app.callback(
    Output('tip-graph', 'figure'),
    [Input("colorscale-dropdown", "value")]
)
def update_tip_figure(colorscale):
    return px.scatter(
        df_color, x="total_bill", y="tip", color="size",
        color_continuous_scale=colorscale,
        render_mode="webgl", title="Tips"
    )

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

Your next question may be, how do i place multiple figures side by side? This is where CSS and stylesheets are important.

You have already added an external stylesheet https://codepen.io/chriddyp/pen/bWLwgP.css, which enables us to better structure our layout using the className component of divs.

The width of a web page is set to 12 columns no matter the screen size. So if we want to have two figures side by side, each occupying 50% of the screen they need to fill 6 columns each.

We can achieve this by nesting another html.Div as our top half row. In this upper div we can have another two divs in which we specify the style according to classname six columns. This splits the first row in two halves

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.express as px
from jupyter_dash import JupyterDash

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df_bar = pd.DataFrame({
    "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
    "Amount": [4, 1, 2, 2, 4, 5],
    "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})

fig = px.bar(df_bar, x="Fruit", y="Amount", color="City", barmode="group")

app.layout = html.Div(children=[
    # All elements from the top of the page
    html.Div([
        html.Div([
            html.H1(children='Hello Dash'),

            html.Div(children='''
                Dash: A web application framework for Python.
            '''),

            dcc.Graph(
                id='graph1',
                figure=fig
            ),  
        ], className='six columns'),
        html.Div([
            html.H1(children='Hello Dash'),

            html.Div(children='''
                Dash: A web application framework for Python.
            '''),

            dcc.Graph(
                id='graph2',
                figure=fig
            ),  
        ], className='six columns'),
    ], className='row'),
    # New Div for all elements in the new 'row' of the page
    html.Div([
        html.H1(children='Hello Dash'),

        html.Div(children='''
            Dash: A web application framework for Python.
        '''),

        dcc.Graph(
            id='graph3',
            figure=fig
        ),  
    ], className='row'),
])

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

这篇关于如何在单个浏览器页面上将多个图形添加到Dash应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆