15

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?

user2808117
  • 4,497
  • 8
  • 27
  • 36

2 Answers2

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:

  1. matplotlib.use("Agg") is optional. It is appropriate for programs that never want to show interactively viewer.
  2. f.add_subplot() all parameters are optional:
dank8
  • 361
  • 4
  • 20
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
  • 5
    I'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