✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚾️ It's finally Baseball season! Root for the home team... & Register for our Sports Analytics Webinar!

Remove all elements in cytoscape

Hi

I’m using a callback to populate the elements in cytoscape component. It all works well when I’m adding elements, but sometimes I want to clear the data out so I tried to return (empty list) from the callback. This doesn’t seem to remove the elements from the screen though. Is there something else I need to do ?

Thanks

Ian

Crickets.

I’ll raise this as bug on GitHub.

Hi @MonkeyChap

Returning an empty list works to remove elements. Here is an example:

Note- See also the section on adding and removing elements in the docs: Callbacks | Dash for Python Documentation | Plotly

import dash
from dash.dependencies import Input, Output, State
import dash_cytoscape as cyto
import dash_html_components as html

app = dash.Dash(__name__)

app.layout = html.Div(
    [
        html.H1("My Cytoscape"),
        html.Button("toggle elements", id="button"),
        cyto.Cytoscape(
            id="cytoscape-two-nodes",
            layout={"name": "preset"},
            style={"width": "100%", "height": "400px"},
            elements=[],
        ),
    ]
)


@app.callback(
    Output("cytoscape-two-nodes", "elements"),
    Input("button", "n_clicks"),
    State("cytoscape-two-nodes", "elements"),
)
def update_output(n_clicks, el):
    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"}},
    ]
    return elements if el == [] else []


if __name__ == "__main__":
    app.run_server(debug=True)

Peek 2021-04-13 07-49

Thanks AnnMarie - that was pretty much what I was doing. I even tried swapping it all to a clientside callback but that didn’t fix it either. In the end, I sorted the problem by creating a whole new cytoscape instance and passing it into the children of the parent Div.

Well, that’s a workaround, but it shouldn’t be necessary. Just curious, what happens if you try to run my example?

Hi

That’s working fine - just tried it.

I’m now wondering if this is something to do with clientside callbacks - we’ve had to make pretty heavy use of them for performance reasons when the app is web deployed. I have noticed that if you replace a component programmatically (e.g. the new cyto component mentioned before as a workaround) the new item isn’t available to clientside callbacks - they come back as undefined.

The non-clearing cyto network is something different though. No errors are raised at all, it’s just that passing an empty list doesn’t seem to clear it. If I pass a list with just one element in, then all the other elements will get cleared.

With all the clientside workarounds, I’m kinda wishing we’d just built the whole thing in Javascript from the start !