Reputation: 25703
How do I create a cycle graph on n
nodes with igraph, either in R or Python?
It should look like this, but for an arbitrary number of nodes:
EDIT: Since it was requested that I should add a code attempt, here's one possibility in R that I found to be too complicated:
n <- 5
make_graph( c(tail(rep(1:n, each=2), -1), 1) )
Upvotes: 1
Views: 469
Reputation: 102519
Try make_ring
if you are using igraph
with R
plot(make_ring(5))
Upvotes: 2
Reputation: 24059
for python you need to install:
pip install python-igraph
pip install pycairo
Then you can use Graph.Ring
from igraph
like below:
import igraph as ig
nodes = 5
g = ig.Graph.Ring(n=nodes, circular=True)
ig.plot(g,vertex_label = range(1,nodes+1))
In R, the relevant igraph function is make_ring()
. You can read in Doc:
Create a ring graph Description A ring is a one-dimensional lattice and this function is a special case of make_lattice.
Usage make_ring(n, directed = FALSE, mutual = FALSE, circular = TRUE)
Upvotes: 2
Reputation: 5232
In R with n
vertices:
n <- 8
seq_len(n) %>%
{c(head(., -1), tail(., -1))} %>%
matrix(ncol = 2) %>%
rbind(c(n, 1)) %>%
graph_from_edgelist(directed = FALSE)
Upvotes: 1