mrsteve
mrsteve

Reputation: 4142

How to plot a complete graph in R?

I want to plot complete graphs in R.

How can I do that? I found only one package on CRAN that does have a function to generate complete graphs. But this package, namely "RnavGraph", didn't install but exited with error status. Searching further seems to be difficult, because of the different meanings of graph, which is not soley associated with graph structures but also with plots.

How can I plot a complete graph in R?

Ps: But I got the following error when I tried to install "RnavGraph":

ERROR: dependencies ‘graph’, ‘RBGL’ are not available for package ‘RnavGraph’
* removing ‘/home/steve/R/x86_64-unknown-linux-gnu-library/3.0/RnavGraph’

The downloaded source packages are in
    ‘/tmp/RtmpIW4p30/downloaded_packages’
Warning message:
In install.packages("RnavGraph") :
  installation of package ‘RnavGraph’ had non-zero exit status

Upvotes: 3

Views: 2909

Answers (1)

Will Beason
Will Beason

Reputation: 3561

Use igraph. Here's a simple way:

library(igraph)

CompleteGraph <- function(n) {
  myEdges <- combn(1:n,2)
  myGraph <- graph(myEdges, directed=FALSE)
  return(myGraph)
}

myGraph <- CompleteGraph(10)

plot(myGraph)

The igraph package lets you make a graph from a list of edges. In this case, I used combn to generate all unique combinations of two numbers from the vector 1:n. When I feed this into the graph function, it creates a graph where every node is connected to every other node. I set directed=false so arrows don't show up when the graph is plotted. The igraph functions adds plotting of graphs to the plot function, so the newly created graph can be plotted as above. (It's easier than typing plot.igraph)

Upvotes: 8

Related Questions