【问题标题】:predict x values from simple fitting and annoting it in the plot通过简单拟合预测 x 值并在图中对其进行注释
【发布时间】:2016-09-24 03:25:19
【问题描述】:

我有一个非常简单的问题,但到目前为止还没有找到简单的解决方案。假设我有一些数据要拟合并显示其 x 轴值,其中 y 是特定值。在这种情况下,假设当 y=0 时,x 值是多少。模型是非常简单的 y~x 拟合,但我不知道如何从那里估计 x 值。总之,

样本数据

library(ggplot2)
library(scales)
df = data.frame(x= sort(10^runif(8,-6,1),decreasing=TRUE), y = seq(-4,4,length.out = 8))

ggplot(df, aes(x = x, y = y)) +
  geom_point() +
  #geom_smooth(method = "lm", formula = y ~ x, size = 1,linetype="dashed",  col="black",se=FALSE, fullrange = TRUE)+
  geom_smooth(se=FALSE)+
  labs(title = "Made-up data") + 
  scale_x_log10(breaks =  c(1e-6,1e-4,1e-2,1),
                labels = trans_format("log10", math_format(10^.x)),limits = c(1e-6,1))+
  geom_hline(yintercept=0,linetype="dashed",colour="red",size=0.6)

我想将 1e-10 输入转换为 10^-10 格式并在绘图上进行注释。正如我在情节中指出的那样。

提前致谢!

【问题讨论】:

  • ggplot2 是图形工具,而不是建模工具。您必须重新创建模型,然后在其上使用 predict 和感兴趣的 x
  • 然后将其添加到绘图中。

标签: r ggplot2 lm


【解决方案1】:

由于geom_smooth() 使用R 函数计算平滑线,您可以在ggplot() 环境之外获得预测值。一种选择是使用 approx() 来获得 x 值的线性近似值,给定预测的 y 值 0

# Define formula
formula <- loess(y~x, df)

# Approximate when y would be 0
xval <- approx(x = formula$fitted, y = formula$x, xout = 0)$y

# Add to plot
ggplot(...) + annotate("text", x = xval, y = 0 , label = yval)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-16
  • 1970-01-01
  • 1970-01-01
  • 2018-01-13
  • 2017-09-05
  • 2019-08-06
  • 1970-01-01
相关资源
最近更新 更多