1

In my boxplot, I needed to modify the whisker definition for only one level of the factor plotted on the x-axis, and used the method given in this answer, which involves splitting the data into two separate frames and plotting them separately. This has the unwanted side effect of obliterating the ordering on the levels of the factor; they are now in the default (alphabetical) ordering.

How can I preserve the level ordering in the original data frame?

Example:

library(ggplot2)

data(diamonds)

# This function extends the whiskers to the full range of the data, rather than
# the default IQR-based range
no.outliers = function(x) {
  setNames(quantile(x, c(0.00, 0.25, 0.50, 0.75, 1.00)), 
           c("ymin", "lower", "middle", "upper", "ymax"))
}

ggplot(diamonds, aes(x=cut, y=price)) +
  geom_boxplot(data=subset(diamonds, cut != 'Ideal')) +
  stat_summary(data=subset(diamonds, cut == 'Ideal'), geom="boxplot",
               fun.data=no.outliers)
Community
  • 1
  • 1
Will
  • 4,241
  • 4
  • 39
  • 48
  • @JasonAizkalns, done! – Will Jan 18 '16 at 20:58
  • 1
    add `scale_x_discrete(drop = FALSE)` – rawr Jan 18 '16 at 21:06
  • Awesome, that works! If you want the rep, feel free to turn that into an answer and I'll accept it. – Will Jan 18 '16 at 21:07
  • The `scale_x_discrete` doesn't appear to change the ordering of the levels in the legend, though (in my actual code I have the equivalent of `fill=cut` as another argument to `aes`). Is there a way to preserve that ordering as well? – Will Jan 18 '16 at 21:14
  • 1
    addressed better [here](http://stackoverflow.com/questions/10002627/ggplot2-0-9-0-automatically-dropping-unused-factor-levels-from-plot-legend) or [here](http://stackoverflow.com/questions/10834382/ggplot2-keep-unused-levels-barplot) – rawr Jan 18 '16 at 21:14
  • 1
    then you would also need `scale_fill_discrete(drop = FALSE)` – rawr Jan 18 '16 at 21:16

0 Answers0