Carl
Carl

Reputation: 7540

Reorder boxplot x-axis based on a count of observations

In this simplified example, I can get the desired outcome which is the x-axis ordered based on the descending number of observations.

But, in order to handle many more levels, which will also vary based on earlier filtering, I would like to calculate the order rather than specify them manually.

I've looked at a few of the reordering examples on this site, but couldn't find one that deals with a count of observations. Is there a way to do that?

library(tidyverse)
library(ggplot2)
data_df <- read_csv("fct, val\na, 12\nb, 12\nc, 2\nb, 14\nc, 4\nc, 6")
data_df <- data_df %>% 
  mutate(fct2 = factor(fct, levels = c("c", "b", "a")))
ggplot(data_df) +
 geom_boxplot(aes(fct2, val)) 

enter image description here

Upvotes: 1

Views: 747

Answers (1)

Samuel
Samuel

Reputation: 3053

A tidyverse solution would be to use the fct_infreq function from the forcats package.

Example:

library(forcats)
library(ggplot2)

ggplot(mtcars, aes(fct_infreq(as.factor(cyl)), mpg)) + geom_boxplot()

# Count of each cylinder type
table(mtcars$cyl)
# 4  6  8 
# 11  7 14 

Upvotes: 4

Related Questions