Reputation:
My teacher uses R and now he is explaining graph theory. I don't want to use R because I use Python and prefer it, so I want to learn NetworkX (NOT Python igraph because I have a lot of problems printing graphs).
The point is that the Python code seems really complicated if compared to R.
I explain myself better: how can you implement this R code
fig <- graph.formula(a-b, c-e-d, i-k-j-g-i, f-g-j-h-f, k-j-h-l-k, h-l-m-h)
on NetworkX ?
Is it possible in just one row? If not, how can I do?
thanks!
Upvotes: 0
Views: 714
Reputation: 4892
If you take a look at the igraph
documentation of formula
the line you have given
fig <- graph.formula(a-b, c-e-d, i-k-j-g-i, f-g-j-h-f, k-j-h-l-k, h-l-m-h)
only creates a graph with the given (undirected) edges and nodes. So you only want to create a graph
, you find all you need in the networkx
tutorial (add_edges_from
method)
import networks as nx
graph = nx.Graph() # undirected as desired
graph.add_edges_from([("a", "b"), ("c","e"), ("e","d"), ("i","k"), ("k", "j"), ("j", "g"), ("g", "i")])
As you see it's a little bit more work (I have stopped after the first three groups).
Upvotes: 1
Reputation: 1013
You can certainly do it in networkX. I don't know if one line, but in very few.
The code below creates a directed graph with the nodes and edges you specified and then draws it. In theory, one could add all edges into one line (and there are quicker ways of doing this), but this code has one line for each comma-separated part of your R code for better readability.
import networkx as nx
G = nx.DiGraph() #Creates empty graph
G.add_nodes_from(range(0,13))#Adds nodes
G.add_edges_from([(0,1)])#Adds directed edges
G.add_edges_from([(2,3),(3,4)])
G.add_edges_from([(8,10),(10,9),(9,6),(6,8)])
G.add_edges_from([(5,6),(6,9),(9,7),(7,5)])
G.add_edges_from([(10,9),(9,7),(7,11),(11,10)])
G.add_edges_from([(7,11),(11,12),(12,7)])
nx.draw(G)
Upvotes: 0