This is my sample data. I want to plot both y1
and y2
against x1
in a single plot. This is what I did:
library(ISLR)
l
You should add two stat_smooth()
calls and add aes()
to show which y
to use.
ggplot(df,aes(x=x1)) +
geom_point(aes(y = y1), shape = 16) +
geom_point(aes(y = y2), shape = 2) +
stat_smooth(aes(y = y1),method = "lm", formula = y ~ x + I(x^2), size = 1) +
stat_smooth(aes(y = y2),method = "lm", formula = y ~ x + I(x^2), size = 1, color = "red")
Or make long format table and then you will need just one call of stat_smooth()
and geom_point()
.
library(tidyr)
df_long <- df %>% gather(variable, value, y1:y2)
ggplot(df_long, aes(x1, value, color = variable)) +
geom_point() +
stat_smooth(method = "lm", formula = y ~ x + I(x^2), size = 1)