Electrino
Electrino

Reputation: 2890

Draw a shape over plot using ggplot in R?

I am wonder how would I draw a loop or shape around certain points on a ggplot, or is it even possible?

I am using both igraph and ggnet2 to create a plot... a toy example is shown below. Basically, I am creating a simple network, using igraph's clustering algorithms to tell what nodes should be clustered together. Then I am using ggnet2 to plot the network and I'm colouring the nodes corresponding to their clusters. I'm using ggnet2 to plot because it is compatible with ggplot2 so I can add additional ggplot2 arguments/parameters to the plot. In the example below, I am actually drawing over the igraph nodes using geom_point.

library(igraph)
library(GGally)

direction <- c(2,1,3,1,4,1,5,1,3,2,4,2,5,2,4,3,5,3,5,4)
gr <- matrix(direction, nrow = 2)
x1 <- 10.59
x2 <- 15.74
x3 <- 5
x4 <- 18
x5 <- 7

RImp <- data.frame(x1,x2,x3,x4,x5)
nam <- names(RImp)
RImp <- as.numeric(RImp)
Rint <- c(2.96, 1.34, 1.27, 1.1, 2.22, 1.24, 3.11,
          2.52, 0.96, 1.08)

net.bg <- make_graph(gr, 5)

com <- cluster_optimal(net.bg)
V(net.bg)$color <- com$membership
group <- V(net.bg)$color
group <- factor(group)
colrs <- adjustcolor( c("yellow", "red", "blue", "black")) 

g <- set_graph_attr(net.bg, "layout", layout_with_kk(net.bg))
colrs <- adjustcolor( c("yellow", "red", "blue", "black")) 
colorC <- colrs[group]


 pp <- ggnet2(g,
             mode = "circle", 
             size = 0,
             label = nam,
             edge.size = Rint, 
             edge.color = "grey") +
  theme(legend.text = element_text(size = 10), legend.position = "none") +
   geom_label(aes(label = nam),nudge_y = 0.08) +
   geom_point(aes(fill = RImp), size = RImp, col = colorC)
pp
 

This will produce something like this: simple clustered network

So, nodes 1,2 and 3 are clustered together... and 4 and 5 are clustered together. But I'm wondering if it is possible to do something like this (I very quickly created this using image editing software):

coloured network

So, in the example above, I want to draw a shape, polygon, or something around certain nodes using ggplot... is this even possible? I don't know where to begin with this!?

Upvotes: 2

Views: 893

Answers (1)

Roman
Roman

Reputation: 17648

you can try

pp + ggalt::geom_encircle(aes(group = c(1,1,2,2,2)), alpha = 0.1, fill = c("red","red", "green","green","green"))

enter image description here

Using your provided code showed nodes x3-x5 in red color, thus I colored them accordingly.

Upvotes: 4

Related Questions