I know there are some questions similar to this but I have tried the suggested answer and I was not able to figure out how to change the number of decimals in stat_compare_means
Maybe it is because I am not comparing all the values against each other but only some of them.
my code is:
library(tidyverse)
library(ggbeeswarm)
library(ggpubr)
set.seed(123)
data <- data.frame(
plot = rep(c("cl", "ct",
"rt", "rl"), each = 10),
value = c(rnorm(10, mean = 3.5, sd = 0.3), # Control lower canopy
rnorm(10, mean = 3.7, sd = 0.3), # Control upper canopy
rnorm(10, mean = 4.0, sd = 0.3), # Released upper canopy
rnorm(10, mean = 4.2, sd = 0.3)) # Released lower canopy
)
summary_data <- data %>%
group_by(plot) %>%
summarise(
value_Mean = mean(value),
value_SE = sd(value) / sqrt(n())
)
comparisons <- list(
c("cl", "ct"),
c("ct", "rt"),
c("rt", "rl"),
c("cl", "rl")
)
ggplot(data, aes(x = plot, y = value)) +
geom_beeswarm(aes(color = plot),size = 5, alpha = 0.6) +
geom_errorbar(
data = summary_data,
aes(y = value_Mean, ymin = value_Mean - value_SE, ymax = value_Mean + value_SE),
width = 0.2, size = 0.8, color = "black"
) +
geom_point(
data = summary_data,
aes(y = value_Mean), color = "red", size = 8
) +
stat_compare_means(
comparisons = comparisons, method = "t.test", label = "p.format",
label.y = c(4.3, 4.8, 5.3, 5.8),
size = 10
)
I tried adding decimal=3
in the label, or add format.pval = function(p) format(p, digits = 3)
I either get no difference or an error appears.
What am I doing wrong? If you could point me to the question that can answer this problem I will highly appreciate it
BR
The canonical solution in ggsignif::geom_signif
-- for which ggpubr::stat_compare_means
is mostly a wrapper -- is to use the map_signif_level=
argument that can take an arbitrary function to format the P-values.
Unfortunately, that argument is hijacked by ggpubr
in a way that only tries to guess whether you want to replace the values by stars using the non-exported .is_p.signif_in_mapping()
.
A much easier solution is to use just a direct geom_signif
, with the two caveats that it takes test=
and y_position=
rather than method=
and label.y=
arguments (with the exact same meaning):
## Replace only the very last ggpubr::stat_compare_means call
... +
ggsignif::geom_signif(
comparisons = comparisons, test = "t.test",
y_position = c(4.3, 4.8, 5.3, 5.8),
size = 1, map_signif_level = \(p) sprintf("%.3f", p)
)