7

I am new to ggplot2 and have problem displaying the regression line for the entire data set together with the regression lines for each group.

So far I can plot regression line based on the group, but I have no success in getting the regression line for the entire data-set on the same plot.

I want all the regression lines with different line style so that they can be easily identified in black and white print.

Here is my code so far:

ggplot(alldata, aes(y = y, x = x, colour= group, shape = group )) +
  geom_point(size = 3, alpha = .8) + 
  geom_smooth(method = "lm", fill = NA , size = 1) 
Henrik
  • 61,039
  • 13
  • 131
  • 152
Arihant
  • 577
  • 8
  • 23

1 Answers1

13

Try placing the colour, shape, linetype aesthetics not in the original call to ggplot2

You can then add the overall line with a different colour

set.seed(1)
library(plyr)
alldata <- ddply(data.frame(group = letters[1:5], x = rnorm(50)), 'group', 
                 mutate, y=runif(1,-1,1) * x +rnorm(10))


ggplot(alldata,aes(y = y, x = x)) +
  geom_point(aes(colour = group, shape = group), size = 3, alpha = .8) + 
  geom_smooth(method = "lm", se = FALSE, size = 1, 
              aes(linetype = group, group = group)) +
  geom_smooth(method = "lm", size = 1, colour = 'black', se = F) +
  theme_bw()

enter image description here

Henrik
  • 61,039
  • 13
  • 131
  • 152
mnel
  • 110,110
  • 27
  • 254
  • 248
  • @mnel thanks a ton! this works like charm. I am working on putting the main regression line in the legend will update my comments when i am able to do so. – Arihant Oct 17 '12 at 16:13