简体   繁体   中英

R - Overlay multiple least squares plots with colour coding

I'm trying to visualize some data that looks like this

line1 <- data.frame(x = c(4, 24), y = c(0, -0.42864), group = "group1")
line2 <- data.frame(x = c(4, 12 ,24), y = c(0, 2.04538, 3.4135), group = "group2")
line3 <- data.frame(x = c(4, 12, 24), y = c(0, 3.14633, 3.93718), group = "group3")
line4 <- data.frame(x = c(0, 3, 7, 12, 18), y = c(0, -0.50249, 0.11994, -0.68694, -0.98949), group = "group4")
line5 <- data.frame(x = c(0, 3, 7, 12, 18, 24), y = c(0, -0.55753, -0.66006, 0.43796, 1.38723, 3.17906), group = "group5")

df <- do.call(rbind, list(line1, line2, line3, line4, line5))

What I'm trying to do is plot the least squares line (and points) for each group on the same plot. And I'd like the colour of the lines and points to correspond to the group.

All I've been able to do is plot the points according to their group

ggplot(data = df, aes(x, y, colour = group)) + geom_point(aes(size = 10))

But I have no idea how to add in the lines as well and make their colours correspond to the points that they are fitting.

I'd really appreciate any help with this. It's turning out to be so much harder than I though it would be.

You can simply add a geom_smooth layer to your plot

ggplot(data = df, aes(x, y, colour = group)) + geom_point(aes(size = 10)) + 
                                               geom_smooth(method="lm",se=FALSE)

method="lm" specifies that you want a linear model

se=FALSE to avoid plotting confidence intervals

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM