Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
890 views
in Technique[技术] by (71.8m points)

r - ggplot2 colour geom_point by factor but geom_smooth based on all data

In ggplot2, the following command p <- qplot(wt, mpg, data=mtcars, colour=factor(cyl)) taken from here plots a scatter plot with each point coloured according to factor

I would like to fit all data with a geom_smooth irrespective of factor but keeping the colour of individual points according to factor. p + geom_smooth(method="lm") does a linear fit on each factor. How do I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this fairly easily by stepping back from the 'qplot' wrapper function and using the 'ggplot' and geometry functions directly.

ggplot(mtcars, aes(x=wt, y=mpg)) +
    geom_point(aes(colour=factor(cyl))) +
    geom_smooth(method="lm")

demo chart

Step 1: Set your initial 'ggplot' settings. These are the settings that you want to be defaults for the geometry functions.

ggplot(mtcars, aes(x=wt, y=mpg))

In this case, we are using the 'mtcars' data for all geometries with 'wt' assigned to the x-axis and 'mpg' assigned to the y-axis. By specifying these at the beginning, we lessen the risk of messing something up when copy-pasting into the geometry functions.

Step 2: Draw the point geometry, using the factors of 'cyl' to color the points. This is what the original 'qplot' function was doing, but we're specifying it a little more explicitly.

    geom_point(aes(colour=factor(cyl)))

Step 3: Draw the smoothed linear model. This is exactly what the OP wrote before, but now that the aesthetic of coloring is no longer part of the defaults, the model draws as intended.

    geom_smooth(method="lm")

Chain it all together with the + et voila!

For reference: You could just as easily do this by being explicit in each layer, like 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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...