Krzysiek - 1 year ago 59

R Question

I would like to draw standard G=(V,E) graph in R either by ggplot or some R built-in functions.

I have a data frame containing vertices coords:

`> V`

x y

1 589.3438 6422.883

2 8762.6921 7789.147

3 7973.0883 4552.745

4 4100.8408 8108.702

5 6049.3329 6547.239

and a zero-one symetric matrix representing edges:

`> E`

[,1] [,2] [,3] [,4] [,5]

[1,] 0 0 0 1 0

[2,] 0 0 1 0 1

[3,] 0 1 0 0 1

[4,] 1 0 0 0 1

[5,] 0 1 1 1 0

I plot vertices using:

`plotGraph <- function() {`

qplot(x,

y,

data=V,

xlim=c(0,SIZE),

ylim=c(0,SIZE),

main="Graph"

)

}

Any help would be appreciated.

Answer Source

If using `igraph`

is an option, I would recommend it. It's a very useful package when working with graphs. Here's how I would do it using igraph:

```
library(igraph)
# convert V and E to matrices
V <- data.matrix(V)
g <- graph_from_adjacency_matrix(E, mode="undirected")
plot.igraph(g, layout = V)
```

Alternatively, if you want a ggplot-flavored method, you can use `ggnet2`

from the `GGally`

package:

```
library(GGally)
V <- data.matrix(V)
# with ggnet2 you don't have to convert E to a graph
ggnet2(net = E, mode = V )
```