Ggplot2: use different colors in different faces

I have something that seems like a very simple problem, but I can’t solve it, since I barely used ggplots2 ... I just want the plot on the left to use the colors in the color1 variable and the graph on the right to use the colors in the color2 variable. This is MWE:

library(reshape2) library(ggplot2) a.df <- data.frame( id=c("a","b","c","d","e","f","g","h"), var1=c(1,2,3,4,5,6,7,8), var2=c(21,22,23,24,25,26,27,28), var3=c(56,57,58,59,60,61,62,63), color1=c(1,2,"NONE","NONE",1,2,2,1), color2=c(1,"NONE",1,1,2,2,"NONE",2) ) a.dfm <- melt(a.df, measure.vars=c("var2","var3")) ggplot(a.dfm, aes(x=value, y=var1, color=color1)) + geom_point(shape=1) + facet_grid(. ~ variable) 

Thanks a lot!

+3
source share
1 answer

I think the easiest approach with your data is to create an extra column that has a color defined appropriately based on the value of variable . Since there are only two possible values ​​that variable can take, this is not so difficult.

 a.dfm2 <- transform(a.dfm, color.use = ifelse(variable=="var2", as.character(color1), as.character(color2))) ggplot(a.dfm2, aes(x=value, y=var1, color=color.use)) + geom_point(shape=1) + facet_grid(. ~ variable) 

enter image description here

+4
source

Source: https://habr.com/ru/post/1268831/


All Articles