Skip to content

Instantly share code, notes, and snippets.

@tirkarthi
Created February 8, 2020 11:22
Show Gist options
  • Save tirkarthi/503eef714ed49ccf59f56fc54f4e942e to your computer and use it in GitHub Desktop.
Save tirkarthi/503eef714ed49ccf59f56fc54f4e942e to your computer and use it in GitHub Desktop.
# python -m pip install dash-cytoscape==0.0.5
import dash
import dash_cytoscape as cyto
import dash_html_components as html
import dash_core_components as dcc
from pprint import pprint
from dash.dependencies import Input, Output, State
app = dash.Dash(__name__)
nodes = [
{
'data': {'id': short, 'label': label},
'position': {'x': 20*lat, 'y': -20*long}
}
for short, label, long, lat in (
('1', 'One', 10, 20),
('2', 'Two', 20, 30),
)
]
edges = [
{'data': {'source': source, 'target': target}}
for source, target in (
('1', '2'),
)
]
default_stylesheet = [
{
'selector': 'node',
'style': {
'background-color': '#BFD7B5',
'label': 'data(label)'
}
},
{
'selector': 'edge',
'style': {
'line-color': '#A3C4BC'
}
}
]
app.layout = html.Div([
html.Div([
html.Button('Add Node', id='btn-add-node', n_clicks_timestamp=0),
html.Button('Remove Node', id='btn-remove-node', n_clicks_timestamp=0)
]),
cyto.Cytoscape(
id='cytoscape-elements-callbacks',
layout={'name': 'circle'},
stylesheet=default_stylesheet,
style={'width': '100%', 'height': '450px'},
elements=edges+nodes
)
])
@app.callback(Output('cytoscape-elements-callbacks', 'elements'),
[Input('btn-add-node', 'n_clicks_timestamp'),
Input('btn-remove-node', 'n_clicks_timestamp')],
[State('cytoscape-elements-callbacks', 'elements')])
def update_elements(btn_add, btn_remove, elements):
# If the add button was clicked most recently
new_elements = elements[:]
edges = new_elements[0]
last_element = new_elements[-1]
print(last_element)
next_id = int(last_element['data']['id']) + 1
new_elements.append({'data': {'id': next_id,
'label': str(next_id),
'position': {'x': next_id * 10,
'y': next_id * 20}
}
})
new_elements.insert(0, {'data': {'source': last_element['data']['id'],
'target': next_id}})
return new_elements
if __name__ == '__main__':
app.run_server(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment