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

ggplot2, plot, r

Solution

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()

Problem

In the following example I create two series of points and plot them using `ggplot2`. I also highlight several points based on their values ``` library(ggplot2) x <- seq(0, 6, .5) y.a <- .1 * x -.1 y.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')) print(ggplot(df) + geom_point(aes(x, y), color=ifelse(df$y<0, 'red', 'black'))) ``` And here is the result Now I want to separate the two `case`s into two facets, keeping the highlighting scheme ``` > print(ggplot(df) + geom_point(aes(x, y), color=ifelse(df$y<0, 'red', 'black')) + facet_grid(case ~. ,)) Error: Incompatible lengths for set aesthetics: colour ``` How can this be acheived?

Original source