Search code examples
rggplot2ggpmisc

How can I scale a plot without affecting the data that is fit?


I have some data that is a bit crowded close to zero. I would thus like to use a logarithmic scale for the axes to get a clearer impression of those points. However, when I do this and I use the very convenient ggpmisc::stat_poly_line function, the fits are done on the scaled data. Can I avoid this somehow?

Below is an example of what I mean.

df <- structure(list(x = c(
  0.01, 0.763333333333333, 12.42, 0.243333333333333,
  49.4066666666667, 2.37333333333333, 1.08333333333333, 0.0533333333333333,
  0.01, 0.37, 0.01, NA
), y = c(
  0.00333333333333333, 0.183333333333333,
  19.7, 0.356666666666667, 38.6566666666667, 3.47, 1.12, 0.0666666666666667,
  0.01, 0.456666666666667, 0.0166666666666667, 0.00333333333333333
)), row.names = c(NA, -12L), class = c("tbl_df", "tbl", "data.frame"))
ggplot2::ggplot(df, ggplot2::aes(x, y)) +
  ggplot2::geom_point() +
  ggpmisc::stat_poly_eq(
    formula = y ~ x + 0,
    mapping = ggplot2::aes(label = paste(ggplot2::after_stat(adj.rr.label)))
  ) +
  ggpmisc::stat_poly_line(formula = y ~ x + 0)
#> Warning: Removed 1 rows containing non-finite values (stat_poly_eq).
#> Warning: Removed 1 rows containing non-finite values (stat_smooth).
#> Warning: Removed 1 rows containing missing values (geom_point).

ggplot2::ggplot(df, ggplot2::aes(x, y)) +
  ggplot2::geom_point() +
  ggpmisc::stat_poly_eq(
    formula = y ~ x + 0,
    mapping = ggplot2::aes(label = paste(ggplot2::after_stat(adj.rr.label)))
  ) +
  ggpmisc::stat_poly_line(formula = y ~ x + 0) +
  ggplot2::scale_x_log10() +
  ggplot2::scale_y_log10()
#> Warning: Removed 1 rows containing non-finite values (stat_poly_eq).
#> Warning: Removed 1 rows containing non-finite values (stat_smooth).
#> Warning: Removed 1 rows containing missing values (geom_point).

Created on 2021-09-27 by the reprex package (v2.0.1)


Solution

  • just do the inverse operation of the logarithm inside the aes of stat_poly_eq

    ggplot2::ggplot(df, ggplot2::aes(x, y)) +
      ggplot2::geom_point() +
      ggpmisc::stat_poly_eq(
        formula = y ~ x + 0,
        mapping = ggplot2::aes(exp(x),exp(y),label = paste(ggplot2::after_stat(adj.rr.label)))
      ) +
      ggpmisc::stat_poly_line(formula = y ~ x + 0) +
      ggplot2::scale_x_log10() +
      ggplot2::scale_y_log10()
    

    enter image description here