从简单的拟合中预测x值并在图中标注它 [英] predict x values from simple fitting and annoting it in the plot

查看:198
本文介绍了从简单的拟合中预测x值并在图中标注它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

样本数据

  library(ggplot2)
库(比例)
df = data.frame(x = sort(10 ^ runif(8,-6,1),decrease = 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 = (break)= c(1e-6,1e-4,1e-2,1),
labels = trans_format(log10,math_format(10 ^ .x)))+
scale_x_log10 ,限制= c(1e-6,1))+
geom_hline(yintercept = 0,linetype =dashed,color =red,size = 0.6)

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



先谢谢你!

解决方案

因为 geom_smooth()使用R函数来计算平滑线,在 ggplot()环境之外的预测值。然后一个选择是使用 approx()得到x值的线性近似值,给定预测的y值 0 $ b

 #定义公式
公式< - 黄土(y〜x,df)

#y近似为0
xval < - approx(x = formula $ fitted,y = formula $ x,xout = 0)$ y

#添加绘制
ggplot(...)+ annotate(text,x = xval,y = 0,label = yval)


I have a very simple question but so far couldn't find easy solution for that. Let's say I have a some data that I want to fit and show its x axis value where y is in particular value. In this case let's say when y=0 what is the x value. Model is very simple y~x for fitting but I don't know how to estimate x value from there. Anyway,

sample data

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)

I would like to convert 1e-10 input to 10^-10 format and annotate it on the plot. As I indicated in the plot.

thanks in advance!

解决方案

Because geom_smooth() uses R functions to calculate the smooth line, you can attain the predicted values outside the ggplot() environment. One option is then to use approx() to get a linear approximations of the x-value, given the predicted y-value 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)

这篇关于从简单的拟合中预测x值并在图中标注它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆