How to conditionally highlight points in ggplot2 facet plots - mapping color to column How to conditionally highlight points in ggplot2 facet plots - mapping color to column r r

How to conditionally highlight points in ggplot2 facet plots - mapping color to column


You should put color=ifelse(y<0, 'red', 'black') inside the aes(), so color will be set according to y values in each facet independently. If color is set outside the aes() as vector then the same vector (with the same length) is used in both facets and then you get error because length of color vector is larger as number of data points.

Then you should add scale_color_identity() to ensure that color names are interpreted directly.

ggplot(df) + geom_point(aes(x, y, color=ifelse(y<0, 'red', 'black'))) +    facet_grid(case ~. ,)+scale_color_identity()

enter image description here


Instead of using scale_..._identity, one can also wrap the color (and fill) aesthetic in I(). It also requires having color defined in aes.

I came across this question, where the OP I guess kind of accidentally made use of I()... ggplot color is not automatically coloring based on group

Not sure I would every make use of that, but I find this kind of fun.

library(ggplot2)x <- seq(0, 6, .5)y.a <- .1 * x -.1y.b <- sin(x)df <- data.frame(x=x, y=y.a, case='a')df <- rbind(df, data.frame(x=x, y=y.b, case='b'))ggplot(df) +   geom_point(aes(x, y, color= I(ifelse(y < 0, 'red', 'black')))) +  facet_grid(case ~. )

Created on 2020-07-01 by the reprex package (v0.3.0)