5

I'm trying to display the equations on the plot using the stat_poly_eq function of ggpmisc.

My problem is how to change the y= ... in the equation, by y1=... and y2=... by referring to the key argument.

I tried to add the eq.with.lhs argument in the mapping but it does not recognize the argument. I tried to pass a vector to the eq.with.lhs argument but it overlapped both elements in each equation...

Do you have a better idea?

In the last case, I could use geom_text after calculating the equation coefficients myself, but it seemed to be a less efficient way to solve the problem.

Here is a reprex of my problem.

data <- data.frame(x = rnorm(20)) %>% 
    mutate(y1 = 1.2*x + rnorm(20, sd=0.2),
           y2 = 0.9*x + rnorm(20, sd=0.3)) %>%
    gather(value = value, key = key, -x)  

ggplot(data, aes(x = x, y = value)) +
    geom_point(aes(shape = key, colour = key)) + 
    stat_poly_eq(aes(label = ..eq.label.., colour = key), 
                 formula = y  ~ poly(x, 1, raw = TRUE),
                 eq.x.rhs = "x",
                 # eq.with.lhs = c(paste0(expression(y[1]), "~`=`~"),
                 #                 paste0(expression(y[2]), "~`=`~")),
                 eq.with.lhs = paste0(expression(y[ind]), "~`=`~"),
                 parse = TRUE) +
    ylab(NULL)
Arienrhod
  • 2,451
  • 1
  • 11
  • 19
AlexC
  • 63
  • 7

1 Answers1

3

I'm not really sure if it's possible to do it through ggpmisc, but you can change the data once the plot is built, like so:

library(tidyverse)
library(ggpmisc)

data <- data.frame(x = rnorm(20)) %>% 
    mutate(y1 = 1.2*x + rnorm(20, sd=0.2),
           y2 = 0.9*x + rnorm(20, sd=0.3)) %>%
    gather(value = value, key = key, -x)  

p <- ggplot(data, aes(x = x, y = value)) +
    geom_point(aes(shape = key, colour = key)) + 
    stat_poly_eq(aes(label = ..eq.label.., colour = key), 
                 formula = y  ~ poly(x, 1, raw = TRUE),
                 eq.x.rhs = "x",
                 eq.with.lhs = paste0(expression(y), "~`=`~"),
                 parse = TRUE) +
    ylab(NULL)
temp <- ggplot_build(p)
temp$data[[2]]$label <- temp$data[[2]]$label %>% 
    fct_relabel(~ str_replace(.x, "y", paste0("y[", 1:2, "]")))
grid::grid.newpage()
grid::grid.draw(ggplot_gtable(temp))

example

Arienrhod
  • 2,451
  • 1
  • 11
  • 19
  • 1
    Very nice work around!! I didn't new the function ggplot_build to modify elements of the ggplot. Thank you very much ;) – AlexC Oct 14 '19 at 17:57