Dash - 在调整窗口大小之前,动态布局不会传播调整大小的图形尺寸

rah*_*f23 7 python plotly viewport-units plotly-dash

在下面的示例 Dash 应用程序中,我尝试创建具有可变行数和列数的动态布局。这种动态网格样式布局将填充各种图形,可以通过下拉菜单等进行修改。

到目前为止,我遇到的主要问题与视口单元有关,并试图适当地设置单个图形的样式以适应动态布局。例如,我正在dcc.Graph()通过视口单位修改组件的样式,其中尺寸(例如heightwidth可能是35vw23vw取决于列数)。当我从3改变的列数为2,例如,heightwidthdcc.Graph()部件清楚地改变,但是这种改变不会反映在实际的呈现布局,直到窗口被物理调整大小(见示例代码下面的图片) .

如何强制dcc.Graph()组件传播这些更改而不必调整窗口大小?

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State

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

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.config.suppress_callback_exceptions = True

app.layout = html.Div([

    html.Div(className='row', children=[

        html.Div(className='two columns', style={'margin-top': '2%'}, children=[

            html.Div(className='row', style={'margin-top': 30}, children=[

                html.Div(className='six columns', children=[

                    html.H6('Rows'),

                    dcc.Dropdown(
                        id='rows',
                        options=[{
                            'label': i,
                            'value': i
                        } for i in [1,2,3,4]],
                        placeholder='Select number of rows...',
                        clearable=False,
                        value=2
                    ),

                ]),

                html.Div(className='six columns', children=[

                    html.H6('Columns'),

                    dcc.Dropdown(
                        id='columns',
                        options=[{
                            'label': i,
                            'value': i
                        } for i in [1,2,3]],
                        placeholder='Select number of columns...',
                        clearable=False,
                        value=3
                    ),

                ])

            ]),

        ]),

        html.Div(className='ten columns', id='layout-div', style={'border-style': 'solid', 'border-color': 'gray'}, children=[])

    ])

])

@app.callback(
    Output('layout-div', 'children'),
    [Input('rows', 'value'),
    Input('columns', 'value')])
def configure_layout(rows, cols):

    mapping = {1: 'twelve columns', 2: 'six columns', 3: 'four columns', 4: 'three columns'}
    sizing = {1: '40vw', 2: '35vw', 3: '23vw'}

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

        html.Div(className=mapping[cols], children=[

            dcc.Graph(
                id='test{}'.format(i+1+j*cols),
                config={'displayModeBar': False},
                style={'width': sizing[cols], 'height': sizing[cols]}
            ),

        ]) for i in range(cols)

    ]) for j in range(rows)]

    return layout

#Max layout is 3 X 4
for k in range(1,13):

    @app.callback(
        [Output('test{}'.format(k), 'figure'),
        Output('test{}'.format(k), 'style')],
        [Input('columns', 'value')])
    def create_graph(cols):

        sizing = {1: '40vw', 2: '35vw', 3: '23vw'}

        style = {
            'width': sizing[cols],
            'height': sizing[cols],
        }

        fig = {'data': [], 'layout': {}}

        return [fig, style]

if __name__ == '__main__':
    app.server.run()
Run Code Online (Sandbox Code Playgroud)

相关截图(图片 1 - 页面加载,图片 2 - 将列更改为 2):

在此处输入图片说明

在此处输入图片说明

小智 5

以下是如何进行:

app.py 必须导入:

from dash.dependencies import Input, Output, State, ClientsideFunction
Run Code Online (Sandbox Code Playgroud)

让我们在 Dash 布局中的某处包含以下 Div:

html.Div(id="output-clientside"),
Run Code Online (Sandbox Code Playgroud)

资产文件夹必须包含您自己的脚本或默认脚本 resizing_script.js,其中包含:

if (!window.dash_clientside) {
    window.dash_clientside = {};
}
window.dash_clientside.clientside = {
    resize: function(value) {
        console.log("resizing..."); // for testing
        setTimeout(function() {
            window.dispatchEvent(new Event("resize"));
            console.log("fired resize");
        }, 500);
    return null;
    },
};
Run Code Online (Sandbox Code Playgroud)

在你的回调中,放这个,不带@:

app.clientside_callback(
    ClientsideFunction(namespace="clientside", function_name="resize"),
    Output("output-clientside", "children"),
    [Input("yourGraph_ID", "figure")],
)    
Run Code Online (Sandbox Code Playgroud)

此时,当您手动调整窗口大小时,会在浏览器中触发调整大小功能。

我们的目标是实现相同的结果,但无需手动调整窗口大小。例如,触发器可以是 className 更新。

因此,我们应用以下更改: 步骤 1:不变

第 2 步:保持不变 第 3 步:让我们在 javascript 文件中添加一个“resize2”函数,它接受 2 个参数:

if (!window.dash_clientside) {
  window.dash_clientside = {};
}
window.dash_clientside.clientside = {
  resize: function(value) {
    console.log("resizing..."); // for testing
    setTimeout(function() {
      window.dispatchEvent(new Event("resize"));
      console.log("fired resize");
    }, 500);
    return null;
  },

  resize2: function(value1, value2) {
    console.log("resizingV2..."); // for testing
    setTimeout(function() {
       window.dispatchEvent(new Event("resize"));
       console.log("fired resizeV2");
    }, 500);
    return value2; // for testing
  }
};
Run Code Online (Sandbox Code Playgroud)

函数“resize2”现在接受 2 个参数,一个用于下面回调中定义的每个 Input。它将在输出中返回“value2”的值,在同一个回调中指定。您可以将其设置回“null”,这只是为了说明。

Step4:我们的回调现在变成:

app.clientside_callback(
    ClientsideFunction(namespace="clientside", function_name="resize2"),
    Output("output-clientside", "children"),
    [Input("yourGraph_ID", "figure"), Input("yourDivContainingYourGraph_ID", "className")],
)    
Run Code Online (Sandbox Code Playgroud)

最后,您需要一个按钮来触发将更改容器的 className 的事件。

假设您有:

daq.ToggleSwitch(
    id='switchClassName',
    label={
        'label':['Option1', 'Option2'],
    },          
    value=False,                                          
),  
Run Code Online (Sandbox Code Playgroud)

以及以下回调:

@app.callback(Output("yourDivContainingYourGraph_ID", "className"), 
              [Input("switchClassName","value")]
              )
def updateClassName(value):
    if value==False:
        return "twelve columns"
    else:
        return "nine columns"
Run Code Online (Sandbox Code Playgroud)

现在,如果您保存所有内容,请刷新,每次按下切换开关时,它都会调整容器大小、触发功能并刷新图形。

鉴于它的完成方式,我认为它也必须可以以相同的方式运行更多的 Javascript 函数,但我还没有检查。

希望它会帮助一些