r - ggplot2 colour geom_point by factor but geom_smooth based on all data -
in ggplot2, following command p <- qplot(wt, mpg, data=mtcars, colour=factor(cyl)) taken here plots scatter plot each point coloured according factor
i fit data geom_smooth irrespective of factor keeping colour of individual points according factor. p + geom_smooth(method="lm") linear fit on each factor. how do this?
you can stepping 'qplot' wrapper function , using 'ggplot' , geometry functions directly.
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point(aes(colour=factor(cyl))) + geom_smooth(method="lm") 
step 1: set initial 'ggplot' settings. these settings want defaults geometry functions.
ggplot(mtcars, aes(x=wt, y=mpg)) in case, using 'mtcars' data geometries 'wt' assigned x-axis , 'mpg' assigned y-axis. specifying these @ beginning, lessen risk of messing when copy-pasting geometry functions.
step 2: draw point geometry, using factors of 'cyl' color points. original 'qplot' function doing, we're specifying little more explicitly.
geom_point(aes(colour=factor(cyl))) step 3: draw smoothed linear model. op wrote before, aesthetic of coloring no longer part of defaults, model draws intended.
geom_smooth(method="lm") chain + et voila!
for reference: being explicit in each layer, so:
ggplot() + geom_point(data=mtcars, aes(x=wt, y=mpg, colour=factor(cyl))) + geom_smooth(data=mtcars, method="lm", aes(x=wt, y=mpg))
Comments
Post a Comment