Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to save networkx 'draw' result to a file or variable instead of displaying it?

Tags:

networkx

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?

like image 873
user2808117 Avatar asked Sep 22 '14 09:09

user2808117


People also ask

How do you visualize a NetworkX graph?

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.

How do I show a NetworkX graph in Python?

You need to add these: node_labels = {node:node for node in G. nodes()}; nx. draw_networkx_labels(G, pos, labels=node_labels) .


2 Answers

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.

like image 198
alabastericestalagtite Avatar answered Oct 19 '22 03:10

alabastericestalagtite


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): {}}}
like image 30
Emilien Avatar answered Oct 19 '22 04:10

Emilien