Skip to content

Instantly share code, notes, and snippets.

@Rekyt
Created November 14, 2017 15:54
Show Gist options
  • Save Rekyt/f9c60449252868a2c0ea2ead11da7dbb to your computer and use it in GitHub Desktop.
Save Rekyt/f9c60449252868a2c0ea2ead11da7dbb to your computer and use it in GitHub Desktop.
# Function to add number ontop of geom_boxplot
library(ggplot2)
library(dplyr)
# /!\ Need to manually change the "groups" if ks_test included
add_groups_and_number = function(given_plot, ks_tests) {
y_range = ggplot_build(given_plot)$layout$panel_params[[1]]$y.range
y_upper = max(y_range)
# Compute table with groups from Kruskal-Wallis test
group_df = ks_tests$groups %>%
tibble::rownames_to_column("cyl") %>%
select(cyl, groups) %>%
mutate(y = y_upper)
group_df$cyl = factor(trimws(group_df$cyl))
# Function to return number of observation
give_n = function(x, y_up = y_upper) {
data.frame(y = y_up*1.06,
label = paste("n =", length(x))
)
}
new_plot = given_plot +
# Kruskal-Wallis group
geom_text(data = group_df, aes(x = cyl, y = y, label = groups,
fill = NULL),
color = "black", size = rel(5)) +
# Give back only length of data
stat_summary(fun.data = give_n, aes(x = as.factor(cyl)), geom = "text")
return(new_plot)
}
plot_cyl_mpg = ggplot(mtcars, aes(x = as.factor(cyl), mpg)) +
geom_boxplot()
ks_test = agricolae::kruskal(mtcars$mpg, trt = as.factor(mtcars$cyl))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment