Reorder x-axis with ggplot

Hello :slight_smile:

Can someone explain me how i reorder the boxplots for the x-axis in ggplot2.

I tried following Code:

ggplot(data = HxH)+
geom_boxplot(aes(x = NenUsers,
y = AbilityRating),
na.rm = TRUE) +
labs(x ="Nen",
y ="Ability",
title = "NenUsers and their Ability")+
theme_bw()

After i run the code the boxplots dont appear in the right order in regard of the median.
Is there an easy way to reorder the x-axis?

If you want the categories on the x axis to be ordered according to the median of AbilityRating, you can use the fct_reorder() function from the forcats package.

library(forcats)
library(ggplot2)
DF <- data.frame(NenUsers = rep(LETTERS[1:4],10),
                 AbilityRating = runif(40))
DF$NenUsers <- fct_reorder(DF$NenUsers, .x = DF$AbilityRating, 
                           .fun = median)

levels(DF$NenUsers)
#> [1] "D" "A" "C" "B"

ggplot(DF, aes(NenUsers, AbilityRating)) + geom_boxplot()

Created on 2022-08-28 by the reprex package (v2.0.1)

2 Likes

Thank you very much :slight_smile:

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.