0

Creating multiple plots makes it necessary to have a common color scale. That's easy by using scale_color_manual. But it gets tricky if not all levels are present in every plot like with this example

doG = function(df) {
  df$g = factor(df$g, levels = c("red_dot", "green_dot", "blue_dot"))
  g = ggplot(df, aes(x = x, y = y, color = g)) + geom_point()
  g + scale_color_manual(values = c("red", "green", "blue"))
}
df = data.frame(x = 1:3, y = c(1,1,1), g = c("green_dot", "blue_dot", "red_dot"))
doG(df)

looks perfectly fine but then

doG(df[1:2,])

destroys all the illusions. Is there some smart way I can reuse the function doGfor subsets where not all factor levels are present?

jakob-r
  • 6,824
  • 3
  • 29
  • 47
  • Possible duplicate of http://stackoverflow.com/questions/10002627/ggplot2-0-9-0-automatically-dropping-unused-factor-levels-from-plot-legend/10002724#10002724 – Henrik Mar 09 '15 at 14:27

1 Answers1

0

Ok. I just came up with that

doG = function(df) {
  ls = c("red_dot", "green_dot", "blue_dot")
  ls.col = c("red", "green", "blue")
  df$g = factor(df$g, levels = ls)
  g = ggplot(df, aes(x = x, y = y, color = g)) + geom_point()
  g + scale_color_manual(values = ls.col[ls %in% df$g])
}
jakob-r
  • 6,824
  • 3
  • 29
  • 47