简体   繁体   中英

Plot two separated models together in ggplot2

I've like to plot two separated models together in ggplot2 and for this I try to put two geom_line() and doesn't work. In my example:

#Artificial data set
Consumption <- c(501, 502, 503, 504, 26, 27, 55, 56, 68, 69, 72, 93)
Gender <- gl(n = 2, k = 6, length = 2*6, labels = c("Male", "Female"), ordered = FALSE)
Income <- c(5010, 5020, 5030, 5040, 260, 270, 550, 560, 680, 690, 720, 930)
df3 <- data.frame(Consumption, Gender, Income)
df3

# GLM Regression 
fm1 <- glm(Consumption~Gender+Income, data=df3, family=poisson)
summary(fm1)

# ANOVA
anova(fm1,test="Chi")
       Df Deviance Resid. Df Resid. Dev  Pr(>Chi)    
NULL                      11    2467.24              
Gender  1   1200.2        10    1267.03 < 2.2e-16 ***
Income  1   1262.9         9       4.16 < 2.2e-16 ***

#Genders are different than I ajusted one model for male and another for Female

#Male model
df4<-df3[df3$Gender=="Male",]
fm2 <- glm(Consumption~Income, data=df4, family=poisson)
summary(fm2)

#Female model
df5<-df3[df3$Gender=="Female",]
fm3 <- glm(Consumption~Income, data=df5, family=poisson)
summary(fm3)

#Predict
df3 = cbind(df3, predM = predict(fm2, data=df3, type = "response"))#Estimate values for male
df3 = cbind(df3, predF = predict(fm3, data=df3, type = "response"))#Estimate values for female


#Plot
ggplot(data=df3, mapping=aes(x=Income, y=Consumption)) + 
  geom_point() +  
  geom_line(mapping=aes(y=predM,x=Income)) +
  geom_line(mapping=aes(y=predF, x=Income)) 
#

And my wrong output plot was:

奇异的

Any member, without create only one model, could help me, please?

I thought it would make more sense to use the male model just on the male data, and the female model just on the female data. Here's an approach that combines the two sets of predictions and binds those to the original data. Then I use tidyr::gather so the actual and predicted Consumption are put into the same column, which makes it simpler to feed into ggplot:

Predictions <- c(predict(fm2, data = df4, type = "response"),
                 predict(fm3, data = df5, type = "response"))
df3_combined <- cbind(df3, Predictions)

library(tidyverse)
df3_combined %>%
  gather(type, value, Consumption, Predictions) %>%
  ggplot(mapping=aes(x=Income, y=value, color = Gender, lty = type)) + 
  geom_point() +  geom_line()

在此处输入图片说明

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