【问题标题】:fullrange isn't extending geom_smooth(method="lm") line beyond the datafullrange 没有将 geom_smooth(method="lm") 线扩展到数据之外
【发布时间】:2019-08-13 22:20:05
【问题描述】:

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

【问题讨论】:

  • 您能否添加有关math_format() 所需的包或自定义函数的信息?
  • 我很抱歉,我应该删除它。它是 scales 包的一部分,用于格式化 x 轴标签。可以删除整个标签 = ... scale_x_log10 的一部分,问题仍然存在。我将编辑上面的代码并将其删除。

标签: r ggplot2 lm


【解决方案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)

但是,由于在比例尺上设置限制会删除超出这些限制的数据,因此灰色误差带不会延伸到行尾。这可以通过将尺度的限制设置得更宽一些来修改,然后再次使用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)

【讨论】:

  • 我不知道我是怎么错过的!!谢谢!限制部分正是我所缺少的。
猜你喜欢
  • 2019-08-21
  • 1970-01-01
  • 2018-10-15
  • 1970-01-01
  • 2020-03-27
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 2015-09-13
相关资源
最近更新 更多