There is strange issue using scale_y_continuous() and trying to plot text after that. e.g. if we remove scale_y_continuous() from below code then it is working fine but if we add scale_y_continuous() to limit y-axis then it is not displaying p-value content.
library(ggplot2)
library(ggpubr)
# Sample data
data <- data.frame(
group = rep(c("A", "B"), each = 20),
value = c(rnorm(20, mean = 50, sd = 10),
rnorm(20, mean = 60, sd = 15))
)
# Create a boxplot with customized y-axis limits
p <- ggplot(data, aes(x = group, y = value)) +
geom_boxplot() +
scale_y_continuous(limits = c(30, 80)) # Adjust the y-axis visible range
# Add p-values using stat_compare_means()
p <- p +
stat_compare_means(comparisons = list(c("A", "B")), label = "p.format")
# Display the plot
print(p)
Setting limits with scale_y_continuous
removes data outside the limits. Instead we can zoom in with coord_cartesian
. In the same function we can turn off clipping, and then update the theme
to expand the plot's upper margin:
library(ggplot2)
library(ggpubr)
ggplot(data, aes(x = group, y = value)) +
geom_boxplot() +
coord_cartesian(ylim = c(30, 80),
clip = 'off') +
stat_compare_means(comparisons = list(c("A", "B")), label = "p.format") +
theme(plot.margin = unit(c(3,0,0,0), 'cm'))
Created on 2023-08-23 with reprex v2.0.2