I am trying to modify how stat_regline_equation
displays the regression line equation on a plot made with ggscatter
from the R package ggpubr
. Specifically, I want to show a consistent number of digits of coefficients, even when some rounded coefficients have trailing zeros, which are typically removed. Here is an example:
library(tidyverse)
library(ggpubr)
diamonds %>%
filter(color %in% c("E", "H", "I")) %>%
ggscatter(x="carat", y="table", add="reg.line") +
facet_wrap(~color) +
stat_regline_equation(label.y.npc = 'top')
Graph I is fine, graph H has one trailing zero removed, and graph E has the slope removed entirely because it rounds to 1.00.
Based on a great answer I got here as well as a different answer here, I tried to modify the package code using trace(ggpubr:::.stat_lm, edit = TRUE)
to modify lines 13 and 14 from
eq.char <- as.character(signif(polynom::as.polynomial(coefs), 2))
to
eq.char <- as.character(formatC(polynom::as.polynomial(coefs), format = "f", digits = 2))
Here is the problem: if you pass a polynom::polynomial
object to signif
or round
, they return another polynom::polynomial
object, but for formatC
or sprintf
they return characters:
coefs = diamonds %>%
filter(color=='E') %>%
stats::lm(table~carat, .) %>%
stats::coef()
coefs %>%
polynom::as.polynomial() %>%
formatC(format='f', digits=2) %>%
class() %>%
print()
coefs %>%
polynom::as.polynomial() %>%
signif(digits = 2) %>%
class() %>%
print()
[1] "character"
[1] "polynomial"
Therefore my attempt to use formatC
above doesn't work. I am guessing that the polynom::polynomial
class has built-in methods for round
and signif
, and none for formatC
, so the output is coerced for the latter. I could potentially try to modify the class definition of polynom::polynomial
, but at this stage I feel like there has to be an easier way to get trailing zeros on the regression equations that display on my graphs. And I am hoping that this is a common enough desire that someone has an easier solution, or at the very least that an answer might be useful to more people besides myself.