在ggplot2中一起绘制两个分离的模型

时间:2019-03-16 23:43:00

标签: r ggplot2 plot

我想在ggplot2中将两个分离的模型绘制在一起,为此,我尝试放置两个geom_line(),但不起作用。在我的示例中:

#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)) 
#

我的错误输出图是:

bizarre

任何成员,只要不创建一个模型,可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

我认为仅在男性数据上使用男性模型,而仅在女性数据上使用女性模型会更有意义。这是一种将两组预测结合在一起并将其绑定到原始数​​据的方法。然后,我使用const max = Number.MAX_SAFE_INTEGER; console.log(max); const maxPlusTwo = max + 2; console.log(maxPlusTwo); const maxPlusTwoBigInt = BigInt("9007199254740993"); console.log(maxPlusTwoBigInt.toString());,将实际和预测的消耗量放在同一列中,这使得将其输入ggplot更为简单:

tidyr::gather

enter image description here