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?
Asked
Active
Viewed 1.1k times
2 Answers
27
Yes! networkx
will draw to a matplotlib figure, and you can use all matplotlib
API thereafter, including saving the file (to chosen format and dpi).
import networkx
import matplotlib
import matplotlib.pyplot
g = networkx.Graph()
g.add_edge(1,2)
fig = matplotlib.pyplot.figure()
networkx.draw(g, ax=fig.add_subplot())
if True:
# Save plot to file
matplotlib.use("Agg")
fig.savefig("graph.png")
else:
# Display interactive viewer
matplotlib.pyplot.show()
Explanatory Notes:
matplotlib.use("Agg")
is optional. It is appropriate for programs that never want to show interactively viewer.f.add_subplot()
all parameters are optional:- 'what is the
fig.add_subplot(111)
argument' (stackoverflow.com) - api documentation
matplotlib.pyplot.subplot()
, explains first args parameter
- 'what is the

dank8
- 361
- 4
- 20

alabastericestalagtite
- 298
- 2
- 6
1
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): {}}}

Emilien
- 2,385
- 16
- 24
-
5I'm not sure if this answers OP's question. To my understanding, OP wants to save the figure of the graph, not the actual information of the graph. @alabastericestalagtite answer is probably the one that should be accepted. – Guillem Cucurull Jul 10 '18 at 17:26