Graphviz has a very specific representation of subgraphs that is
different than NetworkX. With Graphviz subgraphs included in the
main graph data structure.
If you just need to produce a dot file you can use pygraphviz directly
import pygraphviz as pgv
G=pgv.AGraph()
G.add_edge(1,2)
G.add_edge(2,3)
H=G.subgraph([2,3],name='test') # H is not needed but does contain the
graph with edge 2-3
G.write()
$ python tsg.py
strict graph {
subgraph test {
2 -- 3;
}
1 -- 2;
}
Aric
In principle PyGraphviz should work on Windows and some people have had success.
But so far no Windows developers have volunteered to package PyGrapyhviz.
You might try Pydot (which is pure Python).
e.g. (mixed with networkx)
import networkx as nx
import pydot
G=nx.Graph()
G.add_edge(1,2)
G.add_edge(2,3)
P=nx.to_pydot(G) # switch to a Pydot representation
S=pydot.Subgraph('test')
e=pydot.Edge(pydot.Node(2),pydot.Node(3))
S.add_edge(e)
P.add_subgraph(S)
print P.to_string()
The output is different than with PyGraphviz:
$ python tsg2.py
strict graph G {
1;
2;
3;
1 -- 2;
2 -- 3;
subgraph test {
2 -- 3;
}
}
Aric
I am trying to plot the node-node-distance-distribution for a given network (not
the histogram) after several runs or iterations. I have tried some thing like
this
import networkx
import pylab
iterations=20
average=0
for i in range(iterations):
G=networkx.gnm_random_graph(1000,4000)
for n in G:
p=networkx.single_source_shortest_path_length(G,n).values()
lengths.extend(p)
n,bins=pylab.histogram(lengths,bins=max(lengths))
average=average+n/iterations
pylab.plot(bins,average/sum(average))
But am having a problem, bins and average have not the same size. how can make
them to have the same size? is there any routine that can plot this in networkx?
Franck
you could use one of the networkx layout algorithms:
http://networkx.lanl.gov/reference/drawing.html#module-networkx.drawing.layout
They usually return the positions as a dictionary which you can then
pass to one of the drawing mechanisms with keyword pos=dict.
Best,
Moritz
Yes, take a look at the "pydot_layout" function in
https://networkx.lanl.gov/trac/browser/networkx/networkx/drawing/nx_pydot.py
That shows how to use Pydot to produce a layout and read the positions
of the nodes.
Aric
Yes, pydot_layout won't work for you directly but you can use the code
contained within to do what you want. It's not pretty but it will
work.
e.g. you have a pydot graph object called P that you like.
now (from pydot_layout():
D=P.create_dot(prog=prog)
if D=="": # no data returned
print("Graphviz layout with %s failed"%(prog))
print()
print("To debug what happened try:")
print("P=pydot_from_networkx(G)")
print("P.write_dot(\"file.dot\")")
print("And then run %s on file.dot"%(prog))
return
Q=pydot.graph_from_dot_data(D)
node_pos={}
for n in G.nodes():
node=Q.get_node(pydot.Node(n).get_name())
pos=node.get_pos()[1:-1] # strip leading and trailing double quotes
if pos != None:
xx,yy=pos.split(",")
node_pos[n]=(float(xx),float(yy))
Aric