0

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?
C.Robin
  • 1,085
  • 1
  • 10
  • 23
  • 1
    See this question: https://stackoverflow.com/questions/36438883/reorder-stacks-in-horizontal-stacked-barplot-r/36439557#36439557 – Dave2e Jun 04 '21 at 22:30
  • That does show something which could become a solution to (3), but seems pretty complicated. I've found a simpler way -- am posting a solution now. – C.Robin Jun 04 '21 at 22:44

1 Answers1

2
  • 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())

C.Robin
  • 1,085
  • 1
  • 10
  • 23
ktiu
  • 2,606
  • 6
  • 20