0

I have difficulty drawing line in a ggplot. I am reciting the issue discussed here. The solution suggested there doesn't work when I have one more factor introduced in gplot aesthetics. Here is the code.

pp <- ggplot(mtcars, aes(factor(cyl), mpg, colour = factor(cyl))) + geom_boxplot()
df1 <- data.frame(a = c(1, 1:3,3), b = c(39, 40, 40, 40, 39))
df2 <- data.frame(a = c(1, 1,2, 2), b = c(35, 36, 36, 35))
df3 <- data.frame(a = c(2, 2, 3, 3), b = c(24, 25, 25, 24))
pp + geom_line(data = df1, aes(x = a, y = b)) + annotate("text", x = 2, y = 42, label = "*", size = 8) +
geom_line(data = df2, aes(x = a, y = b)) + annotate("text", x = 1.5, y = 38, label = "**", size = 8) +
geom_line(data = df3, aes(x = a, y = b)) + annotate("text", x = 2.5, y = 27, label = "n.s.", size = 8)

This produces an error Error in factor(cyl) : object 'cyl' not found. I know that I am not describing the best data here, but I hope the problem is clear. I want to draw a uni-color line on ggplot and write the significance value above it irrespective of grouping in the plot.

Community
  • 1
  • 1

1 Answers1

1

Your error occurs because ggplot2 is trying to apply colour = factor(cyl) to the lines, which don't have a cyl column in their data. This can be solved by moving that aesthetic to within the geom_boxplot() layer:

pp <- ggplot(mtcars, aes(factor(cyl), mpg)) + geom_boxplot(aes(colour = factor(cyl)))
David Robinson
  • 77,383
  • 16
  • 167
  • 187
  • Worked like a charm. Thanks, @David, but I want to raise a concern that ggplot seems like a complex implementation for simple things. Just for adding the line, I had to do this subtle change, and on top of that, I have to replicate this syntax in `stats_boxplot`. Similar steps I had to take for `position_dodge`. – satyanarayan rao Mar 20 '17 at 18:55
  • @satyanarayanrao ggplot2 is designed with data visualization in mind, rather than custom annotation; when visualizing data it's helpful for aesthetics to be inherited by each layer. In any case, with ggplot2 it's important to get into the habit of thinking about how variables in data map to your resulting layers – David Robinson Mar 20 '17 at 19:02