通过简单拟合预测 x 值并在图中注释

predict x values from simple fitting and annoting it in the plot

我有一个非常简单的问题,但到目前为止找不到简单的解决方案。假设我有一些数据想要拟合并显示其 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 格式并在绘图上对其进行注释。正如我在情节中指出的那样。

提前致谢!

因为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)