C.Robin
C.Robin

Reputation: 1102

Order of categories in ggplot with fill

I've run this code:

#setup
library(tidyverse)
library(skimr)
library(scales)

#import data
tuesdata <- tidytuesdayR::tt_load('2021-05-25')
records <- tuesdata$records

records_tt <- records %>% 
  mutate(track = factor(track), 
         type = factor(type))

#let's create a boxplot
records_tt %>% 
  ggplot(aes(x=record_duration, y=track, fill=type)) + 
  geom_boxplot(alpha=0.6) + 
  theme_minimal() + 
  scale_x_continuous(labels = comma) +
  labs(x = "Record duration", y = "") +
  theme(
    axis.title.x = element_text(
      margin = margin(t = 15)),
    legend.title = element_blank())

Which gives me this plot:

Mario Kart plot

I have three questions though:

  1. What is ggplot using to decide which level of type to place on the top (i.e. why is it currently plotting three lap on the top and single lap on the bottom)?
  2. How do I flip the order of the display, without changing the order of the legend keys (as it makes sense that single is listed on top of three)?
  3. How do I reorder the values of track from lowest mean value of record_duration (independent of type) to highest mean value, instead of the default reverse alphabetical which is currently displayed?

Upvotes: 0

Views: 558

Answers (1)

ktiu
ktiu

Reputation: 2636

  • For question 2: Here is a solution, borrowing from this solution: Switch out the call to geom_boxplot with the following line:
geom_boxplot(alpha=0.6, position=position_dodge2(reverse = T)) +
  • For question 3: here's a solution:
records_tt %>% 
  group_by(track) %>% 
  mutate(mean_duration = mean(record_duration)) %>% 
  ggplot(aes(x = record_duration, y = reorder(track, -mean_duration), fill = type)) + 
  geom_boxplot(alpha=0.6, position=position_dodge2(reverse = T)) +
  theme_minimal() + 
  scale_x_continuous(labels = comma) +
  labs(x = "Record duration", y = "") +
  theme(
    axis.title.x = element_text(
      margin = margin(t = 15)),
    legend.title = element_blank())

Upvotes: 2

Related Questions