Hello community. Please I need help with this code to be able to sort the categories in my chart. Rstudio sorts alphabetically and that is altering my ordinal type varibale. Any suggestion in my code, please?
#Gráfico más elaborado que incluye resultado del test Kruskal Wallis
my_comparisons2 <- list(c("Viajes Cortos", "Viajes Largos"),c("Viajes Cortos","Viajes Medianos"),c("Viajes Cortos","Viajes muy Largos"),c("Viajes Largos","Viajes Medianos"),
c("Viajes Largos","Viajes muy Largos"),c("Viajes Medianos","Viajes muy Largos"))
ggboxplot(bienestaranimal, x = "Tiempo", y = "Pérdidas_económicas",
color = "darkblue", palette = "jco",ordered = TRUE,
xlab = "Tiempo de viaje" ,ylab = "Pérdidas económicas",
)+
stat_compare_means(comparisons = my_comparisons2, label.y = c(13,14.5,16,17.5,19,20.5))+
stat_compare_means(label.y = 20.5)
You can set the order for a "factor" class variable by setting the levels argument, be aware that even if your variable was not a factor already, when mapping categorical variables to certain aesthetics they get coerced into factors automatically, so to keep the desired order you might want to do it explicitly.
levels
an optional vector of the unique values (as character strings) that x might have taken. The default is the unique set of values taken by as.character(x) , sorted into increasing order of x . Note that this set can be specified as smaller than sort(unique(x))