使用 geom_line() ggplot2 扩展回归线

extending regression lines with geom_line() ggplot2

我使用负二项式 glm 来观察海草中脊椎动物的丰度。因为我有一个交互项,所以我预测了一些鱼类丰度值。我希望这些预测的回归线能够到达情节的结尾 space。现在他们都在不同的时间切断,如下例所示:

total<-c(1,0,5,7,9,10,23,45,78,100)
shoots_collected<-c(1,2,3,4,5,6,7,45,67,88)
epi_bio<-c(0.0,11,0.89,1.5,9,5,.04,6,7,.9)
Year<-c(1,1,1,1,2,2,2,2,1,1)
Year<-as.factor(Year)
intertidal<-data.frame(shoots_collected,Year,epi_bio, total)

glm.neg<-glm.nb(total~Year+shoots_collected+epi_bio+shoots_collected*epi_bio, 
data=intertidal)
summary(glm.neg)
abun_shoots2015<-data.frame("shoots_collected"=rep(0:30, rep(5,31)), 
"epi_bio"=rep(c(0,1,2,3,4), 31), "Year"=rep("1", 155))

# then extracted predicted values using:

p2015<-predict(glm.neg, newdata=abun_shoots2015, se.fit=TRUE, type='response')
abun_shoots2015$fit<-p2015$fit
ggplot(intertidal, aes(x=shoots_collected, y=total)) +
scale_x_continuous(limits = c(0, 30))+
scale_y_continuous(limits=c(0,10))+
 geom_point(pch=1)+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==0.0000),], aes(x=shoots_collected, y=fit), col="red")+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==1),], aes(x=shoots_collected, y=fit), col="green")+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==2),], aes(x=shoots_collected, y=fit), col="blue")+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==3),], aes(x=shoots_collected, y=fit), col="yellow")+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==4),], aes(x=shoots_collected, y=fit), col="pink")

我之前使用的是lines()命令,但是切换到geom_lines()所以我可以使用fullrange=TRUE但它仍然没有用。当我尝试绘制线条时,我看到我有一些缺失值,我怀疑这就是为什么有些被切断的原因,但我不知道从这里去哪里。

您不想在这里使用 scale_y_continuous 等,因为它们具有完全修剪超出规定限制的数据的效果。相反,您想限制绘图的范围以仅显示一部分数据。这是用 coord_cartesian() 完成的,如:

ggplot(intertidal, aes(x=shoots_collected, y=total)) +
 coord_cartesian(xlim = c(0, 30), ylim = c(0,10)) + ## KEY!
 geom_point(pch=1)+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==0.0000),], 
           aes(x=shoots_collected, y=fit), col="red")+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==1),], 
           aes(x=shoots_collected, y=fit), col="green")+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==2),], 
           aes(x=shoots_collected, y=fit), col="blue")+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==3),], 
           aes(x=shoots_collected, y=fit), col="yellow")+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==4),], 
           aes(x=shoots_collected, y=fit), col="pink")

此外,我觉得有必要补充一点,通过将 epi_bio 视为一个因素,可以更好地制作您的情节:

ggplot(intertidal, aes(x=shoots_collected, y=total)) +
  coord_cartesian(xlim = c(0, 30), ylim = c(0,10)) + ## KEY!
  geom_point(pch=1) +
  geom_line(data = abun_shoots2015, aes(y = fit, colour = as.factor(epi_bio))) +
  scale_colour_discrete(name = "epi_bio") +
  theme(legend.position = "top")