Search code examples
rggplot2linear-regressionggpmisc

Modifying the decimal mark of stat_poly_eq


I use the stat_poly_eq function from the ggpmisc package to add the regression equation in my ggplots. It works perfectly. However, I'd like to change the decimal mark of the equation from period to comma, and I can't figure out how to do this. Any suggestions?

data(mpg)

ggplot(mpg, aes(y = displ, x = hwy)) +
  geom_point(alpha = 0.5, color = "cadetblue") +
  geom_smooth(method = "lm", se = F, color = "black", size = 0.5) +
  stat_poly_eq(aes(label = paste(after_stat(eq.label),
                                 after_stat(rr.label),
                                 sep = "*plain(\",\")~~")),
               coef.digits = 3)

Solution

  • You can simply swap the periods for commas using gsub in the rr.label. The eq.label is parsed as an expression, so the period needs to be replaced with something like *paste(',')* for this to work:

    ggplot(mpg, aes(y = displ, x = hwy)) +
      geom_point(alpha = 0.5, color = "cadetblue") +
      geom_smooth(method = "lm", se = F, color = "black", size = 0.5) +
      stat_poly_eq(aes(label = paste(gsub('\\.', "*paste(',')*", 
                                          after_stat(eq.label)),
                                     gsub('\\.', ",", after_stat(rr.label)),
                                     sep = "*plain(\",\")~~")),
                   coef.digits = 3, size = 6)
    

    enter image description here