我想使用 sigma.js 来显示一些 DOT 图。但似乎 sigma.js 只支持 json 图格式。
是否有一些 bash 工具或 javascript 模块可以将 DOT 图转换为 json 图?
例如从 DOT 图:
graph {
n1 [Label = "n1"];
n2 [Label = "n2"];
n3 [Label = "n3"];
n1 -- n2;
n1 -- n3;
n2 -- n2;
}Run Code Online (Sandbox Code Playgroud)
转移到 JSON 图:
{
"nodes": [
{
"id": "n0",
"label": "A node",
"x": 0,
"y": 0,
"size": 3
},
{
"id": "n1",
"label": "Another node",
"x": 3,
"y": 1,
"size": 2
},
{
"id": "n2",
"label": "And a last one",
"x": 1,
"y": 3,
"size": 1
}
],
"edges": [
{
"id": "e0",
"source": "n0",
"target": "n1"
},
{
"id": "e1",
"source": "n1",
"target": "n2"
},
{
"id": "e2",
"source": "n2",
"target": "n0"
}
]
}Run Code Online (Sandbox Code Playgroud)
如果您可以使用 python 并安装 3 个包(networkx和pygraphviz和pydot),这里是一个将点图转换为 json 图的简短脚本:
# dot_to_json_graph.py
# http://stackoverflow.com/questions/40262441/how-to-transform-a-dot-graph-to-json-graph
# Packages needed :
# sudo aptitude install python-networkx python-pygraphviz python-pydot
#
# Syntax :
# python dot_to_json_graph.py graph.dot
import networkx as nx
from networkx.readwrite import json_graph
import sys
import json
if len(sys.argv)==1:
sys.stderr.write("Syntax : python %s dot_file\n" % sys.argv[0])
else:
dot_graph = nx.nx_pydot.read_dot(sys.argv[1])
print(json.dumps(json_graph.node_link_data(dot_graph)))
Run Code Online (Sandbox Code Playgroud)
这是您的示例,转换为 json 图:
{"directed": false, "graph": [["node", {"Label": ""}], ["graph",
{"file": "test.dot"}], ["edge", {}], ["name", ""]], "nodes": [{"id":
"n1", "Label": "n1"}, {"id": "n2", "Label": "n2"}, {"id": "n3",
"Label": "n3"}], "links": [{"source": 0, "target": 1, "key": 0},
{"source": 0, "target": 2, "key": 0}, {"source": 1, "target": 1,
"key": 0}], "multigraph": true}
Run Code Online (Sandbox Code Playgroud)
小智 5
我无法在 Windows 和 Linux 中安装pygraphviz,并且最近遇到了同样的问题。networkx 现在支持更轻松地转储为 json,包括 d3.js 格式(此页面中的信息)
我有两种解决方法:
1-使用PyDot
可能很快就会过时!既然Python中有graphviz接口,PyDot可能不会那么频繁地使用。
def dot_to_json(file_in):
import networkx
from networkx.readwrite import json_graph
import pydot
graph_netx = networkx.drawing.nx_pydot.read_dot(file_in)
graph_json = json_graph.node_link_data( graph_netx )
return json_graph.node_link_data(graph_netx)
Run Code Online (Sandbox Code Playgroud)
2-使用graphviz源
如 graphviz 界面文档的这一部分所示,您可以从 .dot 源文件创建图形。
| 归档时间: |
|
| 查看次数: |
7309 次 |
| 最近记录: |