Я хотел бы создать приложение Python Dash с графиком sigma.js и поэтому пытаюсь запустить его с минимальным примером. Моя структура папок выглядит следующим образом:
DashGraph/
├── app3.py
└── assets
└── sigma.min.js
И мой код такой:
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
app = dash.Dash(__name__, suppress_callback_exceptions=True, assets_folder='assets')
app.layout = html.Div(
[
html.H2("Sigma.js Graph"),
html.Div(
id = "graph-container",
children=[
html.Div(id = "sigma-container", style = {"width": "100%", "height": "500px", "border": "1px solid #ccc"}),
],
),
html.Button("Load Graph", id = "load-graph-button"),
dcc.Location(id='url', refresh=False),
html.Div(id='page-content')
]
)
init_sigma_script = """
function initSigmaGraph() {
if (typeof sigma === 'undefined') {
console.error('Sigma.js is not loaded');
return;
}
// Initialize sigma.js with example data
var s = new sigma({
graph: {
nodes: [
{ id: 'n0', label: 'Node 0', x: 0, y: 0, size: 3 },
{ id: 'n1', label: 'Node 1', x: 1, y: 1, size: 3 },
{ id: 'n2', label: 'Node 2', x: 2, y: 2, size: 3 },
],
edges: [
{ id: 'e0', source: 'n0', target: 'n1' },
{ id: 'e1', source: 'n1', target: 'n2' },
{ id: 'e2', source: 'n2', target: 'n0' },
]
},
container: 'sigma-container',
settings: {
defaultNodeColor: '#ec5148'
}
});
// Add interactivity
s.bind('clickNode', function(e) {
alert('Node clicked: ' + e.data.node.label);
});
}
"""
@app.callback(
Output("graph-container", "children"),
[Input("load-graph-button", "n_clicks")],
)
def load_graph(n_clicks):
if n_clicks is None or n_clicks == 0:
return dash.no_update
return html.Div(
[
html.Div(id = "sigma-container", style = {"width": "100%", "height": "500px", "border": "1px solid #ccc"}),
html.Script(init_sigma_script),
html.Script("initSigmaGraph();"),
]
)
if __name__ == "__main__":
app.run_server(debug=True)
Может ли кто-нибудь сказать мне, как я могу получить график сигмы для отображения в html.Div? Каждая помощь, как всегда, очень ценится.
html.Script
нельзя использовать для выполнения кода Javascript:
html.Script
A Script component. Script is a wrapper for the <script> HTML5 element.
CAUTION: <script> is included for completeness, but you cannot execute JavaScript
code by providing it to a <script> element. Use a clientside callback for this purpose instead.
https://dash.plotly.com/dash-html-components/script
Как рекомендует документация, мы можем использовать обратный вызов на стороне клиента:
from dash import Dash, html, dcc
from dash.dependencies import Input, Output
app = Dash(__name__, assets_folder='assets', external_scripts=["https://cdnjs.cloudflare.com/ajax/libs/sigma.js/1.2.0/sigma.min.js"])
app.layout = html.Div(
[
html.Div(id = "dummy-output"),
html.Div(id = "sigma-container", style = {"width": "100%", "height": "500px", "border": "1px solid #ccc"}),
html.Button(id = "load-graph-button", children = "Load Graph"),
]
)
app.clientside_callback(
"""
function(nClicks) {
var s = new sigma(
{
renderer: {
container: 'sigma-container',
type: 'canvas'
},
settings: {
minEdgeSize: 0.1,
maxEdgeSize: 2,
minNodeSize: 1,
maxNodeSize: 8,
}
}
);
// Create a graph object
var graph = {
nodes: [
{ id: "n0", label: "A node", x: 0, y: 0, size: 3, color: '#008cc2' },
{ id: "n1", label: "Another node", x: 3, y: 1, size: 2, color: '#008cc2' },
{ id: "n2", label: "And a last one", x: 1, y: 3, size: 1, color: '#E57821' }
],
edges: [
{ id: "e0", source: "n0", target: "n1", color: '#282c34', type:'line', size:0.5 },
{ id: "e1", source: "n1", target: "n2", color: '#282c34', type:'curve', size:1},
{ id: "e2", source: "n2", target: "n0", color: '#FF0000', type:'line', size:2}
]
}
// Load the graph in sigma
s.graph.read(graph);
// Add interactivity
s.bind('clickNode', function(e) {
alert('Node clicked: ' + e.data.node.label);
});
// Ask sigma to draw it
s.refresh();
}
""",
Output("dummy-output", "children"),
Input("load-graph-button", "n_clicks"),
prevent_initial_call=True
)
if __name__ == "__main__":
app.run_server(debug=True)
Для кода Javascript я использовал этот пример здесь https://www.bsimard.com/2018/04/25/graph-viz-with-sigmajs.html и немного его подкорректировал.