Search code examples
pythonplotly-dashcytoscape

Dash Plotly Cytoscape initial zoom isn't working


I'm trying to create a Cytoscape on Plotly Dash. The zoom value I gave in Cytoscape props does not affect.

cyto.Cytoscape(
    id='my-cytoscape',
    zoom=500,
    layout={"name": "preset"},
    style={"width": "100%", "height": "600px"},
    stylesheet=[{
        "selector": "node",
        "style": {"width": "data(node_size)",
                  "height": "data(node_size)",
                  "label": "data(label)",
                  "backgroundColor": "blue",
                  "fontSize": "11px"},
    },
        {"selector": "edge",
         "style": {"width": 0.4, "curve-style": "bezier"}},
    ],
)

Solution

  • I think the problem is that the preset layout sets fit to True by default (source).

    The documentation tells us the problem with this:

    Initial viewport state
    zoom : The initial zoom level of the graph. Make sure to disable viewport manipulation options, such as fit, in your layout so that it is not overridden when the layout is applied...

    https://github.com/cytoscape/cytoscape.js/blob/e6541de603f5714f572238573ea06ef17503282b/documentation/md/core/init.md#initial-viewport-state

    So you just need to set fit to False in your Cytoscape component's layout property:

    layout = (
        {
            "name": "preset",
            "fit": False,
        },
    )
    

    Also your zoom level was too zoomed in for me when I tested it.

    Minimal fully reproducible example:

    import dash
    import dash_cytoscape as cyto
    import dash_html_components as html
    
    app = dash.Dash(__name__)
    
    app.layout = html.Div(
        [
            cyto.Cytoscape(
                id="cytoscape-two-nodes",
                zoom=5,
                style={"width": "100%", "height": "600px"},
                layout={
                    "name": "preset",
                    "fit": False,
                },
                elements=[
                    {
                        "data": {"id": "one", "label": "Node 1"},
                        "position": {"x": 75, "y": 75},
                    },
                    {
                        "data": {"id": "two", "label": "Node 2"},
                        "position": {"x": 200, "y": 200},
                    },
                    {"data": {"source": "one", "target": "two"}},
                ],
            )
        ]
    )
    
    if __name__ == "__main__":
        app.run_server()