How to reorder boxplot by only one level of a variable?

Hi,

I would like to plot two series of boxplots next to each other, but sorting by the median values of only one series.

Here is my code so far:

library(dplyr)
#> 
#> Attachement du package : 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(ggplot2)

RSC <- tibble(Substance = rep(c(rep("Sub1", 10), rep("Sub2", 10), rep("Sub3", 10)), 2),
              Concentration = c(rep(10, 30), rep(100, 30)),
              AdvantageSubstance = c(seq(-3, length.out = 10), seq(-7, length.out = 10), seq(0, length.out = 10),
                                     seq(-10, length.out = 10), seq(-12, length.out = 10), seq(-20, length.out = 10)))

RSC %>%
  ggplot(aes(x = reorder(Substance, AdvantageSubstance, FUN = median), y = AdvantageSubstance, colour = as.factor(Concentration))) +
  geom_boxplot()

Created on 2019-08-19 by the reprex package (v0.3.0)

I would like to have the graph sorted by the median values when Concentration equals 10 (at the moment, reorder sorts by the median values of all concentrations).

Any ideas / solutions?

Thanks in advance!

I would make a new column of the reordered factor outside of ggplot.

library(dplyr)

library(ggplot2)

RSC <- tibble(Substance = rep(c(rep("Sub1", 10), rep("Sub2", 10), rep("Sub3", 10)), 2),
              Concentration = c(rep(10, 30), rep(100, 30)),
              AdvantageSubstance = c(seq(-3, length.out = 10), seq(-7, length.out = 10), 
                                     seq(0, length.out = 10),
                                     seq(-10, length.out = 10), seq(-12, length.out = 10), 
                                     seq(-20, length.out = 10)))

ReOrdered <- RSC %>% filter(Concentration == 10) %>% 
  mutate(SubstanceNew = reorder(Substance, AdvantageSubstance, FUN = median)) %>% 
  select(Substance, SubstanceNew)
RSC %>% inner_join(ReOrdered, by = "Substance") %>% 
  ggplot(aes(x = SubstanceNew, y = AdvantageSubstance, colour = as.factor(Concentration))) +
  geom_boxplot()

Created on 2019-08-19 by the reprex package (v0.2.1)

1 Like

Great! Many thanks indeed :slight_smile:

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