I would like to generate a graph's drawing but save it to file instead of displaying it to screen. Is there a way to do that?
NetworkX has its own drawing module which provides multiple options for plotting. Below we can find the visualization for some of the draw modules in the package. Using any of them is fairly easy, as all you need to do is call the module and pass the G graph variable and the package does the rest.
You need to add these: node_labels = {node:node for node in G. nodes()}; nx. draw_networkx_labels(G, pos, labels=node_labels) .
Yes! Networkx will draw to a matplotlib figure, and you can use all matplotlibs API thereafter, including saving the file (to chosen format and dpi).
import networkx as nx
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
g = nx.Graph()
g.add_edge(1,2)
f = plt.figure()
nx.draw(g, ax=f.add_subplot(111))
f.savefig("graph.png")
The line matplotlib.use("Agg")
is optional, but it is appropriate for programs that never want to show matplotlib plots interactively.
Here is the documentation you are looking for, with many solutions. I may add that if no one is supposed to read or modify the created file (it's just a storing format), you may use pickle. If you need a more generic format because the graph will be used in other tools you may prefer graphML or Json.
Example:
>>> cube = nx.hypercube_graph(2)
>>> nx.write_gpickle(cube,"cube.gpickle")
>>> readCube = nx.read_gpickle("cube.gpickle")
>>> cube.edge
{(0, 1): {(0, 0): {}, (1, 1): {}}, (1, 0): {(0, 0): {}, (1, 1): {}}, (0, 0): {(0, 1): {}, (1, 0): {}}, (1, 1): {(0, 1): {}, (1, 0): {}}}
>>> readCube.edge
{(0, 1): {(0, 0): {}, (1, 1): {}}, (1, 0): {(0, 0): {}, (1, 1): {}}, (0, 0): {(0, 1): {}, (1, 0): {}}, (1, 1): {(0, 1): {}, (1, 0): {}}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With