Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 264
Fernanda Peres Avatar asked Jan 31 '26 00:01

Fernanda Peres


1 Answers

data(mpg)
library(ggpmisc)

my_formula <- y ~ x
myformat <- "y = %s %s x, R²: %s"

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(
    formula = my_formula, output.type = "numeric",
    mapping = aes(
      label = 
        sprintf(
          myformat,
          format(stat(coef.ls)[[1]][[1, "Estimate"]], digits = 3, decimal.mark = ","),
          format(stat(coef.ls)[[1]][[2, "Estimate"]], digits = 2, decimal.mark = ","),
          format(stat(r.squared), digits = 2, decimal.mark = ",")))
  ) 

I have elaborated my answer based on this post.

I hope this helps you! 😀

like image 115
Esther Avatar answered Feb 01 '26 14:02

Esther



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!