Display graph without saving using pydot
You can render the image from pydot
by calling GraphViz
's dot
without writing any files to the disk. Then just plot it. This can be done as follows:
import io
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import networkx as nx
# create a `networkx` graph
g = nx.MultiDiGraph()
g.add_nodes_from([1,2])
g.add_edge(1, 2)
# convert from `networkx` to a `pydot` graph
pydot_graph = nx.drawing.nx_pydot.to_pydot(g)
# render the `pydot` by calling `dot`, no file saved to disk
png_str = pydot_graph.create_png(prog='dot')
# treat the DOT output as an image file
sio = io.BytesIO()
sio.write(png_str)
sio.seek(0)
img = mpimg.imread(sio)
# plot the image
imgplot = plt.imshow(img, aspect='equal')
plt.show()
This is particularly useful for directed graphs.
See also this pull request, which introduces such capabilities directly to networkx
.
Here's a simple solution using IPython:
from IPython.display import Image, display
def view_pydot(pdot):
plt = Image(pdot.create_png())
display(plt)
Example usage:
import networkx as nx
to_pdot = nx.drawing.nx_pydot.to_pydot
pdot = to_pdot(nx.complete_graph(5))
view_pydot(pdot)
Based on this answer (how to show images in python), here's a few lines:
gr = ... <pydot.Dot instance> ...
import tempfile, Image
fout = tempfile.NamedTemporaryFile(suffix=".png")
gr.write(fout.name,format="png")
Image.open(fout.name).show()
Image
is from the Python Imaging Library