Changing the number of decimal places on stat_regline_equation

Hi guys,

I'm trying to change the number of decimal places or even significant figures on my stat_regline_equation. My sample code is as follows:

meta_data <- read.csv("data/raw_data/norm_expression_matrix_meta.csv")

# subset the meta data to just display age, the genes, the delta ct, and subject ID
subset_meta_data <- meta_data[1:279,1:36]

# plot scatter plot graph
ggplot(subset_meta_data, mapping = aes(x = Age,
                                       y = FLG )) +
  
  # include bestfit line with equation and R^2
  # add in upper and lower limit lines as well
  
  geom_point() +
  geom_smooth(method = "lm", se = TRUE) +
  stat_regline_equation(label.x = 20, label.y = 15) +
  stat_cor(label.x = 60, label.y = 15, digits = 4) +
  stat_regline_equation(label.x = 40, label.y = 15, aes(label = ..rr.label..)) +
  geom_hline(aes(yintercept = 11.5), color = "red") +
  geom_hline(aes(yintercept = 8.88), color = "purple")

I tried using "signif()" function as well, but was having issues. The reason this is important, is because R rounds up the y-intercept value in the equation. In this case it's 11: y = -0.013x +11. However, it should be 10.81 (according to excel). Is there a way to get around this, so it doesn't round up?

I think that unfortunately ggpubr has not been designed to let you tailor this in a super elegant way, though perhaps you could request that from the ggpubr creators as a feature request.

You can however completely control what is printed, but you may need to do additional work, to cobble together the elements you want. Here is an example. First I show the out of the box rounding that ggpubr naturally gives you. thereafter I demonstrate arbitrary precision (i chose 3 decimal points, but you can do anything here).

library(tidyverse)
library(ggpubr)

#out of the box
ggscatter(mtcars, x = "wt", y = "mpg", add = "reg.line") +
  stat_cor(label.x = 3, label.y = 34) +
  stat_regline_equation(label.x = 3, label.y = 32)



# construct your own formatting 

(mylm <- lm(data=mtcars,
           formula=mpg~wt))

(my_eq <- scales::comma(mylm$coefficients,accuracy = 0.001))
(my_eq_text <- paste0("y = ", my_eq[[1]], " ",my_eq[[2]],"x"))

ggscatter(mtcars, x = "wt", y = "mpg", add = "reg.line") +
  stat_cor(label.x = 3, label.y = 34) +
  stat_regline_equation(label.x = 3, label.y = 32,
                        mapping=aes(label=my_eq_text),
                        output.type="text")

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.