Tek bir tarayıcı sayfasında Dash uygulamasına birden çok grafik nasıl eklenir?

Aug 18 2020

görüntü açıklamasını buraya girin

Aynı sayfada resimde gösterilen birden fazla grafiği nasıl eklerim? Tek sayfada olduğu gibi daha fazla grafik eklemek için sayfa düzenini güncellemek için aşağıdaki koda html.Div bileşenleri eklemeye çalışıyorum, ancak bu yeni eklenen grafikler bir sayfada gösterilmiyor, resimde sadece eski grafik gösteriliyor. Yüklenen görüntüde 3 kez gösterilen grafiği tarayıcıdaki dash uygulamasının tek sayfasına eklemek için hangi öğeyi değiştirmeliyim?


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)

Yanıtlar

16 KristianHaga Aug 18 2020 at 14:57

Aynı rakamı birden çok kez eklemek için, sadece app.layout. Örnek olarak aşağıdaki kodu genişlettim.

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)

Düzeni yapılandırma şeklim, html.Divbileşenleri yerleştirmektir. Her şekil ve ilgili başlıklar, metin vb html.Div. İçin uygulamamızda yeni bir 'satır' oluşturan başka bir tane oluşturuyoruz.

Unutulmaması gereken tek şey, farklı bileşenlerin benzersiz kimliklere ihtiyaç duymasıdır . Bu örnekte, aynı grafiği iki kez görüntüledik, ancak bunlar tam olarak aynı nesne değiller. dcc.GraphAynı plotly.express figürünü kullanarak iki nesne yapıyoruz.

Dinamik olan başka bir figür eklediğim başka bir örnek daha yaptım . Açılır menüden her yeni renk ölçeği seçildiğinde ikinci rakam güncellenir. Dash yalanlarının gerçek potansiyeli buydu. Bu öğreticide geri arama işlevleri hakkında daha fazla bilgi edinebilirsiniz.

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)

Bir sonraki sorunuz olabilir, birden çok figürü yan yana nasıl yerleştirebilirim? CSS ve stil sayfalarının önemli olduğu yer burasıdır.

Daha önce , div bileşenini https://codepen.io/chriddyp/pen/bWLwgP.csskullanarak classNamedüzenimizi daha iyi yapılandırmamızı sağlayan harici bir stil sayfası eklediniz .

Bir web sayfasının genişliği, ekran boyutu ne olursa olsun 12 sütuna ayarlanır. Bu yüzden, yan yana iki figür istiyorsak, her biri ekranın% 50'sini kaplar, her birinin 6 sütunu doldurması gerekir.

Bunu, html.Divüstteki yarı sıraya bir başkasını yerleştirerek başarabiliriz . Bu üst div'de, stili sınıf adına göre belirlediğimiz başka iki div'imiz olabilir six columns. Bu, ilk sırayı ikiye böler

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)