问题
The advantage of using matplotlib with NetworkX is the ease with which one can produce PDF, PNG, and SVG outputs.
import networkx as nx
import matplotlib.pyplot as plt
G1 = nx.Graph()
G.add_nodes_from(["a", "b"])
G.add_edge("a", "b")
nx.draw_networkx(G)
plt.savefig("graph.pdf")
plt.savefig("graph.png")
plt.savefig("graph.svg")
How can this code be modified to produce HTML5/Javascript Canvas code? Concrete code, however trivial, is more helpful than rooting for a given library. Sigmajs seems promising, if not for the scanty documentation.
回答1:
The most straightforward way to achieve what you want is to simply export the graph as GEXF with Networkx using:
G = nx.path_graph(4)
nx.write_gexf(G, "test.gexf")
Then in your HTML you can use the sigma.js GEXF parser like so:
<div id="container">
<style>
#graph-container {
top: 0;
bottom: 0;
left: 0;
right: 0;
position: absolute;
}
</style>
<div id="graph-container"></div>
</div>
<script>
/**
* The plugin sigma.parsers.gexf can load and parse the GEXF graph file,
* and instantiate sigma when the graph is received.
*
* The object given as the second parameter is the base of the instance
* configuration object. The plugin will just add the "graph" key to it
* before the instanciation.
*/
sigma.parsers.gexf('data/arctic.gexf', { // path to graph here
container: 'graph-container'
});
</script>
If you want to look at a real live example, I suggest this blog post at the bottom.
DISCLAIMER: it's my blog ;)
来源:https://stackoverflow.com/questions/35004519/producing-a-canvas-output-from-networkx