Stat smooth

54 views
Skip to first unread message

Ross

unread,
Nov 18, 2012, 12:47:51 PM11/18/12
to ggp...@googlegroups.com
Following code plots 3 separate regression lines for each factor of 'cyl':

(mtcarsPlot <- ggplot(mtcars,aes(x=disp,y=mpg,colour=as.factor(cyl))) + 
  geom_point(size=8) +
  stat_smooth(method='lm')) 

How can I plot a single regression line (no subsetting for 'cyl')?

Ben Bolker

unread,
Nov 18, 2012, 1:25:23 PM11/18/12
to ggp...@googlegroups.com
stat_smooth(method="lm",aes(group=1))

Dennis Murphy

unread,
Nov 18, 2012, 6:09:11 PM11/18/12
to Ross, ggp...@googlegroups.com
Hi:

Another way to do this is to remove the color aesthetic from the ggplot() call and move it to geom_point() instead:

ggplot(mtcars,aes(x=disp,y=mpg)) +
    geom_point(aes(color = as.factor(cyl))) +
    geom_smooth(method = lm)

Placing the color aesthetic in the ggplot() call means that it will be expected to be present in *all* subsequent layers, which forces one to use group = 1 as an aesthetic in geom_smooth() to override the expectation of separate lines by levels of the color aesthetic.

Both methods are instructive and worth understanding: e.g., if I had multiple layers in a ggplot, most of which used color (say, for example, colored boxplots and points) then I'd probably put the color aesthetic in ggplot() and use the group = 1 device for geom_smooth() as Ben showed. OTOH, if I only wanted color in one or two layers of a multi-layer ggplot, I would declare them as aesthetics in the geom(s) of interest and not in ggplot(), as in my code above.

Dennis

--
You received this message because you are subscribed to the ggplot2 mailing list.
Please provide a reproducible example: https://github.com/hadley/devtools/wiki/Reproducibility
 
To post: email ggp...@googlegroups.com
To unsubscribe: email ggplot2+u...@googlegroups.com
More options: http://groups.google.com/group/ggplot2

Reply all
Reply to author
Forward
0 new messages