如何在 Dash 中编写一个应用程序布局,使两个图形并排?

How to write an app layout in Dash such that two graphs are side by side?

我想在 Dash by Plotly 中并排绘制两个图表(而不是一个在另一个之上)。 教程没有并排绘制图形的示例。

我写app.layout的方式如下

app.layout = html.Div(className = 'row', children=

    [
        html.H1("Tips database analysis (First dashboard)"),
        dcc.Dropdown(id='d',
                     options = col_options,
                    value = 'Sun'),
        dcc.Graph(id="graph1"),
        dcc.Graph(id="graph2")
    ]

)

但在此之后 graph1 出现在 graph2 上方而不是并排

您可以通过将图表包装在 div 中并向每个图表添加 display: inline-block css 属性 来实现此目的。

app.layout = html.Div(className='row', children=[
    html.H1("Tips database analysis (First dashboard)"),
    dcc.Dropdown(),
    html.Div(children=[
        dcc.Graph(id="graph1", style={'display': 'inline-block'}),
        dcc.Graph(id="graph2", style={'display': 'inline-block'})
    ])
])

结果

编辑

我从包装 div 中删除了 display: flex 属性,而是将 display: inline-block 属性 添加到每个图表中。这使得第二张图不会被截断,而是会堆叠在较小的屏幕上。

以防有人想在地块之间使用水平 spacer,这样中间的 space 就会被 spacer 填充并且地块位于左外侧和右外侧 - 以下方法在我的案例中是成功的。

第 1 步:

assets 文件夹添加到项目的根文件夹。此资产文件夹允许包含 .css 和 .js 文件。这允许将自定义 css 添加到 dash 应用程序,如此处所述:https://dash.plotly.com/external-resources#:~:text=Adding%20Your%20Own%20CSS%20and%20JavaScript%20to%20Dash%20Apps&text=Including%20custom%20CSS%20or%20JavaScript,are%20included%20in%20this%20folder.

第 2 步:

style.css 文件添加到您的 assets 文件夹,其中包含以下 css:

.parent {
  display: flex;
  flex-direction: row;
}

.spacer {
  flex-grow: 1;
}

.plot{
    display: flex;
    width: 50%
}

@media screen and (max-width: 1200px) {
  .parent{
    flex-direction: column;
  }
  .plot{
    width: 100%
  }
}

dash 项目会自动找到 .css 文件,只要它存储在 assets 文件夹中即可。

第 3 步:

html.Div() 包裹你的地块,并在地块之间放置另一个 html.Div()。根据[中定义的css 类设置html.Div()dcc.Graph()className参数=56=] 文件


 app.layout = html.Div([
    html.Div(className='row', children=[
        dcc.Dropdown(),
        html.Div(className='parent', children=[
            dcc.Graph(id='plot1', className='plot'),
            html.Div(className='spacer'),
            dcc.Graph(id='plot2', className='plot'),
        ])
    ]),
])

编辑:

向 css 添加了媒体查询和一些额外的样式,现在它也可以用作响应式解决方案