fullrange不会将geom_smooth(method =“lm”)行扩展到数据之外

问题描述 投票:2回答:1

当使用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行在数据末尾停止:

r ggplot2 lm
1个回答
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()again来修改:

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

© www.soinside.com 2019 - 2024. All rights reserved.