Re-ordering Boxplot x-Axis?

Hi,

I have a dataframe where I have binned diameters of pipe for plotting into a boxplot. The plot will correctly place the boxes in order except for any diameters at 10 inches, for some reason it will place it first on the x-axis.

I have reproduced the error using the iris dataframe; is there any way to manipulate the plot so that it starts at the smallest diameter, up to 10 and then "over 10 in"?

I have poked around scale_x_discrete put cannot see where I would change the output. I have also tried mutate_if(Bin, is.character, as.factor) to see if changing to a factor would help but it did not.

d <- iris
boxplot_d <- d %>%
  mutate(Bin = case_when(Petal.Length  > 6.5 ~ 'Over 10 in',
                            Petal.Length >= 6 ~ '10 in.',
                            Petal.Length >= 5 ~ '5 in.',
                            Petal.Length >= 4  ~ '4 in. ',
                            Petal.Length >= 3  ~ '3 in. ',
                            Petal.Length < 3 ~ '2 in to 3 in'))

p1 <- ggplot(data=boxplot_d, aes(x=Bin, y=Sepal.Length)) +
  geom_boxplot(color = "black", alpha = 0.2)
p1

Colin

Hi, to order your data you need to turn it into a factor. The simplest way to do this is with the help of the {forcats} package, for example with the function fct_reorder().
Or you can do it manually (the default is alphabetically):

factor(Bin, levels = c("2 in to 3 in", "3 in.", "4 in.", "5 in.", "10 in.", "Over 10 in")

Here is a reprex:

library(tidyverse)

d <- iris
boxplot_d <- d %>%
  mutate(Bin = case_when(Petal.Length  > 6.5 ~ 'Over 10 in.',
                         Petal.Length >= 6 ~ '10 in.',
                         Petal.Length >= 5 ~ '5 in.',
                         Petal.Length >= 4  ~ '4 in.',
                         Petal.Length >= 3  ~ '3 in.',
                         Petal.Length < 3 ~ '2 in. to 3 in.'))

p1 <- boxplot_d %>% 
  group_by(Bin) %>% 
  mutate(med = median(Petal.Length, na.rm = T)) %>% 
  ggplot(aes(x=fct_reorder(Bin, med), y=Sepal.Length)) +
    geom_boxplot(color = "black", alpha = 0.2)
p1


p2 <- boxplot_d %>% 
  mutate(Bin = factor(Bin, levels = c("2 in. to 3 in.", "3 in.", "4 in.", "5 in.", "10 in.", "Over 10 in."))) %>% 
  ggplot(aes(x=Bin, y=Sepal.Length)) +
  geom_boxplot(color = "black", alpha = 0.2)
p2

Created on 2020-07-15 by the reprex package (v0.3.0)

I tried to pipe that after mutate but it did not work. On its own, it just created a vector with 6 factor levels and did not re-order the dataframe

Oh sorry, my original suggestion is missing, I have updated the post!

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