aphalo / ggpmisc

R package ggpmisc is an extension to ggplot2 and the Grammar of Graphics
https://docs.r4photobiology.info/ggpmisc
94 stars 6 forks source link

Wrong equation when using `formula=y~I(1/x)` #40

Closed orgadish closed 1 year ago

orgadish commented 1 year ago

When I use stat_poly_eq with formula=y~I(1/x), the wrong equation is printed. In the case of the code below, it should be y = 1/x,

but instead it gives:

y = -0.00033 + 1.01x

library(ggplot2)
set.seed(0)

tibble::tibble(x=1:100, y=1/x + rnorm(100, sd=0.01)) |>   
  ggplot(aes(x, y))+
  geom_point()+
  geom_smooth(formula=y~I(1/x), method="lm", se=F)+
  ggpmisc::stat_poly_eq(ggpmisc::use_label("eq"), formula=y~I(1/x), method="lm")

Created on 2023-06-29 with reprex v2.0.2

aphalo commented 1 year ago

@orgadish If you transform on-the-fly the data you pass as explanatory variable, you need to manually replace the x in the equation. This is rather straightforward if you are familiar with R expressions (see help(plotmath)). There are also a few examples in the package vignette. I hope the examples below help you. stat_poly_equation() by default assumes that a polynomial on x is being fitted.

Thanks for raising this issue! However, this is a feature, not a bug, as it makes building the equation relatively easy. If this is not well explained, it is a problem with the documentation. I will try to make sure that the help page has a suitable example.

library(ggpmisc)
#> Loading required package: ggpp
#> Loading required package: ggplot2
#> 
#> Attaching package: 'ggpp'
#> The following object is masked from 'package:ggplot2':
#> 
#>     annotate
#> Registered S3 method overwritten by 'ggpmisc':
#>   method                  from   
#>   as.character.polynomial polynom

set.seed(0)

tb <- tibble::tibble(x=1:100, y=1/x + rnorm(100, sd=0.01))

p <-
  ggplot(tb, aes(x, y))+
  geom_point()+
  geom_smooth(formula=y~I(1/x), method="lm", se=F)

p + ggpmisc::stat_poly_eq(ggpmisc::use_label("eq"), formula=y~I(1/x), method="lm", 
                        eq.x.rhs = "~~x^{-1}")


p + ggpmisc::stat_poly_eq(ggpmisc::use_label("eq"), formula=y~I(1/x), method="lm", 
                        eq.x.rhs = "~\"/ x\"")


p + ggpmisc::stat_poly_eq(ggpmisc::use_label("eq"), formula=y~I(1/x), method="lm", 
                        eq.x.rhs = "*\" \"*frac(1, x)")

Created on 2023-06-30 with reprex v2.0.2

aphalo commented 1 year ago

Help for stat_poly_eq(), stat_quant_eq() and stat_ma_eq() updated to make clear the need to manually pass a matching argument to eq.x.rhs when a transformation is applied to x within the model formula.