Home > Net >  How can I add specific point on boxplot in ggplot2 in different colour?
How can I add specific point on boxplot in ggplot2 in different colour?

Time:10-11

I have a dataframe with two columns variable and value:

df<- data.frame(c(rep('v1',4),rep('v2',4)),c(1,2,3,4,5,6,7,8))
colnames(df) <- c('variable', 'value')

Next I make a boxplot with ggplot2:

library(ggplot2)
j <- ggplot(df, aes(factor(variable), value)) 
j   geom_boxplot()   facet_wrap(~variable, scale="free")

My problem now is to add with geom_point specific points which were not present in the original dataframe to v1 and v2 boxplots in different (red) colour. How can I do it?

CodePudding user response:

Based on your description, I think this might be what you want.

df<- data.frame(c(rep('v1',4),rep('v2',4)),c(1,2,3,4,5,6,7,8))
colnames(df) <- c('variable', 'value')
df2 <- data.frame(c(rep('v1',4),rep('v2',4)),c(2,5,6,1,2,3,5,3))
colnames(df2) <- c('variable', 'value')


library(ggplot2)
ggplot(df, aes(factor(variable), value))   geom_boxplot()   facet_wrap(~variable, scale="free")  
  geom_point(data = df2,aes(x=variable, y=value),color = 'red')

enter image description here

CodePudding user response:

If you want to add a point to both facets then see the example here:

library(ggplot2)
j <- ggplot(df, aes(factor(variable), value))   
  geom_boxplot()    
  facet_wrap(~variable, scales="free")

j    
  geom_point(aes(x=1, y=2), col="red", size=3) 
  geom_point(aes(x=1, y=2.5), col="green", size=3)

enter image description here

  • Related