I know this is an old question, but I was looking for the same thing: How to get dot notation from a graph in NetworkX?
(If you are only interested in the answer, skip this paragraph. I actually wanted to display a NetworkX multigraph, but even though NetworkX is powerful python library for manipulation of networks and graphs, it has fairly limited options when it comes displaying (rendering) graphs and networks. NetworkX uses Matplotlib to provide basic functionality for visualizing graphs, which doesn't have the option for visualizing multigraph. NetworkX is not intended for visualizing graphs so in NetworkX documentation they recommend using some of graph visualization tools, Cytoscape, Gephi, Graphviz. All of this tools have some kind of python interfaces but the best one (easiest and simplest to use) is graphviz which supports the DOT language of the Graphviz drawing software. Visualizing graphs in graphviz is very simple and convenient, you can use one short line such as graph.view() which by default creates a PDF file and opens it in your system's default PDF viewer, but you can also view and create image files such as SVG and PNG. So it would be ideal to convert NetworkX graph to graphviz graph and to do that you need to convert NetworkX graph to DOT notation which can then be read by graphviz.)
Solution by Aric is simple and works for printing out DOT notation of graph, but is kind of a hack and also in my case, I need to save DOT notation in string variable so I can use it to create a graph in graphviz from that DOT notation.
networkx.drawing.nx_pydot.write_dot(source) is a function that creates DOT format and saves it to a path (file handle). Code of this function is:
@open_file(1, mode='w')
def write_dot(G, path):
P = to_pydot(G)
path.write(P.to_string())
return
And this gives us the solution for answer:
from networkx import path_graph
from networkx.drawing.nx_pydot import to_pydot
G = path_graph(4)
dot = to_pydot(G).to_string()
print(dot)
Function to_pydot (source) uses pydot library to create pydot.Dot object which has to_string (source) method that returns string representation of graph in DOT language.
P.S.:
To render a DOT source code in graphviz you can do something like this:
from graphviz import Source
src = Source(dot) # dot is string containing DOT notation of graph
src.view()
P.P.S.:
Two following pictures show difference when you use Matplotlib (left side of image) and graphviz (right side of image) to visualize graph networkx.margulis_gabber_galil_graph(3):
