全范围未将geom_smooth(method =“ lm”)行扩展到数据之外

时间:2019-03-22 21:19:23

标签: r ggplot2 lm

使用geom_smooth进行绘制时,我试图将lm线扩展到数据范围之外。但是,设置fullrange = TRUE似乎无法解决问题。

如代码所示,我已使用coord_cartesian和scale_x_log10将xlim设置为超出数据范围。

library(ggplot2)

    df<-data.frame(Time=c(1:9 %o% 10^(2:3),10^4),Shift=seq(0.01,0.03,length.out=19),Treatment=2.2)
    df<-rbind(df,data.frame(Time=c(1:9 %o% 10^(2:3),10^4),Shift=seq(0.02,0.06,length.out=19),Treatment=2.4))
    df<-rbind(df,data.frame(Time=c(1:9 %o% 10^(2:3),10^4),Shift=seq(0.06,0.14,length.out=19),Treatment=2.6))
    df<-rbind(df,data.frame(Time=c(1:9 %o% 10^(2:3),10^4),Shift=seq(0.09,0.22,length.out=19),Treatment=2.8))

    myPlot <- ggplot(df,aes(x=Time,y=Shift,col=as.factor(Treatment))) +
      scale_y_log10(breaks = c(1 %o% 10^(-2:1)), minor_breaks = c(1:9 %o% 10^(-1:2)),labels=paste0(c(1 %o% 10^(0:3)),"%")) +
      scale_x_log10(breaks = c(1 %o% 10^(2:9)), minor_breaks = c(1:9 %o% 10^(0:10))) +
      labs(color="Treatment") +
      coord_cartesian(xlim=c(100,1E9),ylim=c(0.001,1))+
      theme_bw() +
      annotation_logticks() +
      geom_point()+
      geom_smooth(method="lm",fullrange=TRUE)
    plot(myPlot)

lm行在数据结尾处停止

1 个答案:

答案 0 :(得分:1)

如果将限制设置在scale_*_log10()内部而不是coord_cartesian()中,则线性模型将显示在整个范围内:

myPlot <- ggplot(df,aes(x=Time,y=Shift,col=as.factor(Treatment))) +
  scale_y_log10(limits = c(0.001, 1), breaks = c(1 %o% 10^(-2:1)), minor_breaks = c(1:9 %o% 10^(-1:2)),labels=paste0(c(1 %o% 10^(0:3)),"%")) +
  scale_x_log10(limits = c(100, 1e9), breaks = c(1 %o% 10^(2:9)), minor_breaks = c(1:9 %o% 10^(0:10))) +
  labs(color="Treatment") +
  theme_bw() +
  annotation_logticks() +
  geom_point()+
  geom_smooth(method="lm",fullrange=TRUE)
plot(myPlot)

enter image description here

但是,由于在刻度上设置限制会删除超出这些限制的数据,因此灰色误差带不会延伸到行尾。可以通过以下方式修改此限制:将比例尺的限制设置得更宽一些,然后再次使用coord_cartesian()

myPlot <- ggplot(df,aes(x=Time,y=Shift,col=as.factor(Treatment))) +
  scale_y_log10(limits = c(0.001, 3), breaks = c(1 %o% 10^(-2:1)), minor_breaks = c(1:9 %o% 10^(-1:2)),labels=paste0(c(1 %o% 10^(0:3)),"%")) +
  scale_x_log10(limits = c(100, 1e9), breaks = c(1 %o% 10^(2:9)), minor_breaks = c(1:9 %o% 10^(0:10))) +
  labs(color="Treatment") +
  coord_cartesian(xlim=c(100,1E9),ylim=c(0.001,1)) +
  theme_bw() +
  annotation_logticks() +
  geom_point()+
  geom_smooth(method="lm",fullrange=TRUE)
plot(myPlot)

enter image description here