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

佐手、 提交于 2019-11-27 08:38:51

问题


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!


回答1:


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)



来源:https://stackoverflow.com/questions/37455512/predict-x-values-from-simple-fitting-and-annoting-it-in-the-plot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!