python - 破折号 - 动态布局不会传播调整大小的图形尺寸,直到调整窗口大小

标签 python plotly plotly-dash viewport-units

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

到目前为止,我遇到的主要问题与视口(viewport)单位有关,并试图适本地设置各个图形的样式以适应动态布局。例如,我正在通过视口(viewport)单位修改 dcc.Graph() 组件的样式,其中尺寸(例如 heightwidth可能是 35vw23vw,具体取决于列数)。例如,当我将列数从 3 更改为 2 时,dcc.Graph() 组件的 heightwidth 显然是已更改,但是在实际调整窗口大小之前,此更改不会反射(reflect)在实际呈现的布局中(请参阅示例代码下方的图像)。

如何强制 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()

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

enter image description here

enter image description here

最佳答案

下面是如何进行:

app.py 必须导入:

from dash.dependencies import Input, Output, State, ClientsideFunction

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

html.Div(id="output-clientside"),

asset 文件夹必须包含您自己的脚本或默认脚本 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;
    },
};

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

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

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

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

因此,我们应用以下更改: 第一步:不变

第二步:不变 第 3 步:让我们在 javascript 文件中添加一个“resize2”函数,它有两个参数:

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
  }
};

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

第四步:我们的回调现在变成了:

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

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

假设您有:

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

以及以下回调:

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

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

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

希望对大家有帮助

关于python - 破折号 - 动态布局不会传播调整大小的图形尺寸,直到调整窗口大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55462861/

相关文章:

python - 如何创建带参数的测试类?

python - 未创建 Django 测试表

python - Python 中带有 Plotly 表值的手动色标

r - 在 R 中使用 Plotly 绘制显示毫秒的时间戳

python - 尝试在 Spyder IPython 控制台中初始化 Dash 时出错

plotly - 我可以在 Dash 中加载存储为 HTML 文件(使用 Plotly 的 python 库生成)的图形吗?

python - psql 类型错误 : not all arguments converted during string formatting

python - 求解 Dijkstra 算法 - 通过两条边传递成本/双亲

python - 用于多方面直方图的独立大小的桶

python - 在回调 Dash 中使用 2 个输入动态更新下拉选项