단일 브라우저 페이지에서 Dash 앱에 여러 그래프를 추가하는 방법은 무엇입니까?
여기에 이미지 설명 입력
같은 페이지에 그림으로 표시되는 여러 그래프를 어떻게 추가합니까? 다음 코드에 html.Div 구성 요소를 추가하여 페이지 레이아웃을 업데이트하여 단일 페이지에 더 많은 그래프를 추가하려고하지만 새로 추가 된 그래프는 페이지에 표시되지 않고 그림에 이전 그래프 만 표시됩니다. 업로드 된 이미지에 표시된 그래프를 브라우저의 대시 앱 한 페이지에 3 번 추가하려면 어떤 요소를 수정해야합니까?
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)
답변
동일한 그림을 여러 번 추가하려면 app.layout
. 예제로 아래 코드를 확장했습니다.
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)
![](https://post.nghiatu.com/assets/images/s/7i4HK.png)
레이아웃을 구조화 한 방법은 html.Div
구성 요소 를 중첩하는 것 입니다. 모든 그림과 해당 제목, 텍스트 등에 대해 html.Div
응용 프로그램에서 새로운 '행'을 만드는 다른 하나 를 만듭니다.
한 가지 명심해야 할 점 은 구성 요소마다 고유 한 ID 가 필요 하다는 것 입니다. 이 예에서는 동일한 그래프가 두 번 표시되지만 정확히 동일한 객체는 아닙니다. 우리는 dcc.Graph
동일한 플롯을 사용하여 두 개의 객체를 만들고 있습니다.
동적 인 또 다른 그림을 추가 한 또 다른 예를 만들었습니다 . 두 번째 그림은 드롭 다운 메뉴에서 새 컬러 스케일을 선택할 때마다 업데이트됩니다. 이것이 Dash 거짓말의 진정한 잠재력이었습니다. 이 튜토리얼 에서 콜백 함수에 대해 자세히 읽을 수 있습니다.
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)
![](https://post.nghiatu.com/assets/images/s/BzKJa.png)
다음 질문은 여러 그림을 나란히 배치하는 방법입니다. 여기서 CSS와 스타일 시트가 중요합니다.
div https://codepen.io/chriddyp/pen/bWLwgP.css
의 className
구성 요소를 사용하여 레이아웃을 더 잘 구성 할 수 있는 외부 스타일 시트를 이미 추가했습니다 .
웹 페이지의 너비는 화면 크기에 관계없이 12 열로 설정됩니다. 따라서 두 개의 그림을 나란히 놓으려면 각각 화면의 50 %를 차지하고 각각 6 개의 열을 채워야합니다.
우리는 다른 html.Div
것을 우리의 위쪽 절반 행으로 중첩함으로써 이것을 달성 할 수 있습니다 . 이 상위 div에는 classname에 따라 스타일을 지정하는 또 다른 두 개의 div가 있습니다 six columns
. 첫 번째 행을 두 개로 나눕니다.
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)
![](https://post.nghiatu.com/assets/images/s/Cq6EA.png)