How to correctly select points on ggplot2 graphs that use faces

In the following example, I create two series of points and draw them with ggplot2 . I also highlight several points based on their values

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

And here is the result

First result

Now I want to split two case into two faces, preserving the allocation 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 achieved?

+4
source share
1 answer

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

Then you must add scale_color_identity() to make sure the 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

+11
source

All Articles