I have seen similar questions and solutions but none as far as I can see relatable to geom_text()
in particular. Any guidance is greatly appreciated.
Say I want a plot point estimates and confidence intervals of:
# create tbl
ni <- tribble(
~ method, ~ mean_difference, ~ lo95, ~ hi95,
"NC", 3.235762, -0.5063099, 6.977835,
"IPTW", 3.256231, -0.5063099, 6.977835,
"EM", 5.642857, -1.995181, 13.280896,
)
Next I create a string var pasting together [rounded] mean_difference, lo95, and hi95 — which will be specified as the label for geom_text
# convert to point estimate and confidence intervals to strings (to keep trailing zeros for plot)
to_string <- function(
var,
n_digits = 1,
n_small = 1){
as.character(format(round(var, digits = n_digits), nsmall = n_small))
}
ni <- ni %>%
mutate(
mean_difference_lab = to_string(mean_difference),
lo95_lab = to_string(lo95),
hi95_lab = to_string(hi95),
lab = paste(
mean_difference_lab,
" (",
lo95_lab,
"-",
hi95_lab,
")",
sep = "")
)
This parses correctly in console.
print(ni$lab)
And yet, the trailing zeros are removed from the string when I plot it as:
ni %>%
ggplot(aes(x = mean_difference, y = method)) +
geom_point(
size = 6,
shape = 18) +
geom_errorbarh(aes(
xmin = lo95,
xmax = hi95,
height = 0
)) +
geom_text(aes(
family = 'Courier',
label = lab),
parse = TRUE,
nudge_y = -0.2) +
scale_x_continuous(breaks = seq(- 6, 14, 2))
Can any help spare my blushes, please?