Display graph without saving using pydot
Question
I am trying to display a simple graph using pydot.
My question is that is there any way to display the graph without writing it to a file as currently I use write function to first draw and then have to use the Image module to show the files.
However is there any way that the graph directly gets printed on the screen without being saved ??
Also as an update I would like to ask in this same question that I observe that while the image gets saved very quickly when I use the show command of the Image module it takes noticeable time for the image to be seen .... Also sometimes I get the error that the image could'nt be opened because it was either deleted or saved in unavailable location which is not correct as I am saving it at my Desktop..... Does anyone know what's happening and is there a faster way to get the image loaded.....
Thanks a lot....
Solution
I'm afraid pydot
uses graphviz
to render the graphs. I.e., it runs the executable and loads the resulting image.
Bottom line - no, you cannot avoid creating the file.
OTHER TIPS
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, assuming g
is a pydot
graph:
from cStringIO import StringIO
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 -> pydot
pydot_graph = G.to_pydot()
# render pydot by calling dot, no file saved to disk
png_str = pydot_graph.create_png(prog='dot')
# treat the dot output string as an image file
sio = StringIO()
sio.write(png_str)
sio.seek(0)
img = mpimg.imread(sio)
# plot the image
imgplot = plt.imshow(img, aspect='equal')
plt.show(block=False)
This is particularly useful for directed graphs, because the matplotlib
capabilities of networkx
are severely limited for such graphs.
See also this pull request, which introduces such capabilities directly to networkx
. What remains is for someone to write an interface to load and plot the layout generated by GraphViz
as the ones for MATLAB
on File Exchange GraphViz interface, MATLAB GraphViz Layout importer, GraphViz4Matlab
.
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