Reputation: 1357
In the following example, I follow on from the following link, in which we learn the basic to creating a log regression model.
data(mtcars)
dat <- subset(mtcars, select=c(mpg, am, vs))
logr_vm <- glm(vs ~ mpg, data=dat, family=binomial)
library(ggplot2)
ggplot(dat, aes(x=mpg, y=vs)) + geom_point() +
stat_smooth(method="glm", method.args=list(family="binomial"), se=T) +
theme_bw()
Now I want to create a second log model where we predict a new outcome vs2
.
How can I use ggplot2
to show the two models with different colours?
dat$vs2 <- with(dat, ifelse(mpg > 20, 1, vs))
so that the secondary log model is ....
logr_vm2 <- glm(vs2 ~ mpg, data=dat, family=binomial)
Upvotes: 0
Views: 391
Reputation: 35307
When fitting the models with ggplot
itself, and you only have a few models, you can easily add a legend by manually mapping a model name to colors inside aes
. The rest will then be taken care of.
Addionally, I use geom_count
instead of geom_point
to show that we have overlapping values here, and add some colors to show your different categories:
ggplot(dat, aes(x = mpg)) +
geom_count(aes(y = vs, col = mpg > 20), alpha = 0.3) +
stat_smooth(aes(y = vs, fill = 'm1'), col = 'black',
method = "glm", method.args = list(family = "binomial")) +
stat_smooth(aes(y = vs2, fill = 'm2'), col = 'black',
method = "glm", method.args = list(family = "binomial")) +
scale_size_area() +
scale_color_discrete(h.start = 90) +
theme_bw()
Upvotes: 4