Home > Blockchain >  Grouping points when plotting multiple data frames in ggplot in R?
Grouping points when plotting multiple data frames in ggplot in R?

Time:03-10

I have several data frames that I want to plot on the same graph. However, I would like to circle or enclose points (something similar to ggforce::geom_mark_ellipse() but any solution will do) that have the same row index. For example, if I have some data and make a plot like below:

library(ggplot2)
df <- data.frame(x = c(1, 5, 2, 8 , 10),
                 y = c(5, 1, 8, 3, 8))


df1 <- data.frame(x = c(1.7, 5.8, 3, 7.5 , 9.2),
                  y = c(5.3, 1.1, 8, 3.6, 7.6))


df2 <- data.frame(x = c(1.2, 5.3, 1.8, 8.2 , 10.3),
                  y = c(5.1, 1.3, 7.6, 3.2, 8.2))


ggplot(df, aes(x = x, y = y))  
  geom_point()  
  geom_point(data = df1, aes(x = x, y = y, col = 'red'))  
  geom_point(data = df2, aes(x = x, y = y, col = 'blue'))  
  theme_bw()   
  theme(legend.position = 'none')

This creates a plot like this: example point plot

What Im trying to do is circle the groups by their row index. That is, all row 1's will be grouped together from all data frames... all row 2's will be grouped together etc.

I suspect I will have to somehow combine all the data frames... but Im not sure how exactly to do that!? any suggestions as to how I could do this?

CodePudding user response:

To draw the circles around groups of points, one way would be to use the geom_encircle() function from the ggalt package. enter image description here

If you don't want them all black, you can map z to a different aesthetic.

ggplot(df_all, aes(x=x, y=y, color=origin))  
  geom_point()  
  geom_encircle(aes(fill=z), color=NA, alpha=0.2)

enter image description here

  • Related