Reputation: 359
I wanted to add the difference between two lines to a ggplot2
.
In this example, between the lines of the two groups defined by x2
.
How can this be done?
y=rbinom(100,1,.4)
x1=rnorm(100, 3, 2)
x2=rbinom(100, 1, .7)
sub = data.frame(y=y, x1=x1, x2=x2)
ggplot(sub, aes(x1, y, color = x2)) +
stat_smooth(method = "glm", family = binomial, formula = y ~ poly(x1,3))
Upvotes: 2
Views: 1970
Reputation: 98429
There are two things you should change in your code. First, inside stat_smooth()
use x
and y
and not the actual variable names (function will know that your x
values are x1
). Second, wrap x2
inside factor()
to have two distinct colors.
ggplot(sub, aes(x=x1, y=y, color = factor(x2))) +
stat_smooth(method = "glm", family = binomial, formula = y ~ poly(x,3))
Upvotes: 3