DHAsselbergs
DHAsselbergs

Reputation: 13

Reorder boxplot in rstudio

I am trying to reorder a boxplot based on the median.

mymonths <- c("Jan","Feb","Mar",
              "Apr","Mei","Jun",
              "Jul","Aug","Sep",
              "Okt","Nov","Dec")
df1 <- nycflights13::flights %>% 
  filter(dep_delay > 10) %>%
  select(month, arr_delay) %>% 
  filter(arr_delay < 480) %>%
  mutate(Maand  = mymonths[month])

ggplot(data = df1, mapping = aes(x = arr_delay, y = Maand)) +
  geom_boxplot(outlier.colour = 'red', outlier.alpha = 0.1) +
  labs(x = "Vertraging bij aankomst", caption = "Vluchten die uit New York vertrekken") +
  ggtitle("Vertraging van vluchten per maand (in min)")

now i thought i could either use the function reorder() or fct_reorder(), i would fill in something like fct_reorder(Maand, arr_delay, fun = median) into the aes() of x. (tried switching "Maand"and "arr_delay" but it also doesn't work) The boxplot without reorder looks perfect but once I use reorder it gives me something very weird.

any help would be great!

Upvotes: 0

Views: 202

Answers (2)

廖健龙
廖健龙

Reputation: 58

I tried fct_reorder(Maand, arr_delay, .fun = median) and it looks good.

ggplot(data = df1, mapping = aes(x = arr_delay, y = fct_reorder(Maand, arr_delay, .fun = median))) +
  geom_boxplot(outlier.colour = 'red', outlier.alpha = 0.1) +
  labs(x = "Vertraging bij aankomst", caption = "Vluchten die uit New York vertrekken") +
  ggtitle("Vertraging van vluchten per maand (in min)")

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388862

Try :

library(ggplot2)
ggplot(data = df1, mapping = aes(x = arr_delay, 
       y = forcats::fct_reorder(Maand, arr_delay))) +
  geom_boxplot(outlier.colour = 'red', outlier.alpha = 0.1) +
  labs(x = "Vertraging bij aankomst", 
       caption = "Vluchten die uit New York vertrekken") +
  ggtitle("Vertraging van vluchten per maand (in min)")

If you want the bars in opposite order use y = forcats::fct_reorder(Maand, -arr_delay).

Upvotes: 0

Related Questions