R 在ggplot2中一起绘制两个分离的模型
我想在ggplot2中绘制两个分离的模型,为此,我尝试放置两条几何线,但不起作用。在我的例子中:R 在ggplot2中一起绘制两个分离的模型,r,ggplot2,plot,R,Ggplot2,Plot,我想在ggplot2中绘制两个分离的模型,为此,我尝试放置两条几何线,但不起作用。在我的例子中: #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(50
#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))
#
我的错误输出图是:
任何成员,只要不创建一个模型,都可以帮助我,好吗?我认为在男性数据上使用男性模型,在女性数据上使用女性模型会更有意义。这里有一种结合两组预测并将其与原始数据绑定的方法。然后我使用tidyr::gather,这样实际消耗量和预测消耗量就放在同一列中,这样就更容易输入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()
不清楚您期望的输出是什么。