2

Using the dataset mpg, I am able to plot the three-way relationship between city mpg, highway mpg and class model. I use the following code (using ggplot2) which outputs the graph shown in attached file Boxplot.png.

ggplot(mpg,aes(cty,hwy))+
  aes(color=class)+
  geom_boxplot()+
  facet_grid(.~class, scales='free')+
  theme(axis.text.x = element_text(angle = -90, vjust = 1, hjust = 0))+
  scale_x_continuous('City mpg')+
  scale_y_continuous('Highway mpg')+
  theme(legend.position="none")

Question:

  1. I want to display the boxplots in order of increasing median. How do I do it?

  2. Can I display the median value on top each boxplot?

Sinha
  • 431
  • 1
  • 5
  • 12

2 Answers2

2
require(ggplot2)

aggregate(mpg$hwy, by=list(mpg$class), median)

mpg$class <- factor(mpg$class, levels = c("compact", "midsize", "subcompact",
                                          "2seater", "minivan", "suv", "pickup"))

ggplot(mpg,aes(cty,hwy))+
  aes(color=class)+
  geom_boxplot()+
  facet_grid(.~class, scales='free')+
  theme(axis.text.x = element_text(angle = -90, vjust = 1, hjust = 0))+
  scale_x_continuous('City mpg')+
  scale_y_continuous('Highway mpg')+
  theme(legend.position="none")

enter image description here

You can also display the median. Here's a good explanation / example:

How to display the median value in a boxplot in ggplot?

The example is:

library(plyr)
library(ggplot2)

p_meds <- ddply(p, .(TYPE), summarise, med = median(TOTALREV))

ggplot(p,aes(x = TYPE, y = TOTALREV)) + 
    geom_boxplot() + 
    geom_text(data = p_meds, aes(x = TYPE, y = med, label = med), 
              size = 3, vjust = -1.5)
Community
  • 1
  • 1
Hack-R
  • 22,422
  • 14
  • 75
  • 131
-1

What I often do is to make the class variable a factor, where the levels is ordered as you want. This way your facet graphs are ordered as you wish.

To display median value on top, I often redefine the class variable such as compact (med = 26)

Kota Mori
  • 6,510
  • 1
  • 21
  • 25
  • 1
    A code-containing answer would be more in keeping with this website's mandate. Handwaving ^H^H^H^H^Huntested solutions are not much valued. – IRTFM Sep 18 '16 at 02:19