0

I am trying to make a boxplot and also add a legend to it:

boxplot(mpg~factor(gear),data=mtcars,par(las=2),range=0,col=rainbow(3))
abline(h=median(mtcars$mpg),lty=3)
abline(h=25,lty=6)
legend("bottomright",c("Median mileage","Mileage@25"),lty=c(3,6))

However, I am not being able to order the x-axis ticks. What do I do if I want to change the order to 4-3-5? Can you also show how to do this using ggplot2? My trial with ggplot2:

bp <- ggplot(mtcars,aes(x=gear,y=mpg))
order <- c(4,3,5)
bp+geom_boxplot(aes(colour=gear))+scale_x_discrete(limits=order)+geom_hline(yintercept=median(mtcars$mpg),linetype=2)+geom_hline(yintercept=25,linetype=8)

I am not being able to add the linetype legend in this case, however am able to change the order of the x-axis labels.

Thomas
  • 43,637
  • 12
  • 109
  • 140
Ayan
  • 145
  • 2
  • 16
  • possible duplicate of [Order Bars in ggplot2 bar graph](http://stackoverflow.com/questions/5208679/order-bars-in-ggplot2-bar-graph) – Henrik Nov 10 '14 at 09:57
  • See also [**here**](http://kohske.wordpress.com/2010/12/29/faq-how-to-order-the-factor-variables-in-ggplot2/). – Henrik Nov 10 '14 at 09:58

1 Answers1

0

If you want to order your boxplots and have a discrete variable, you need to convert to factors:

library(ggplot2)
ord <- c(4,3,5)
md.mpg <- median(mtcars$mpg)
bp <- ggplot(mtcars,aes(x = as.factor(gear), y = mpg))
bp+geom_boxplot(aes(colour = as.factor(gear))) +
  scale_x_discrete(limits = as.factor(ord)) +
  geom_hline(yintercept = md.mpg, linetype = 2) +
  annotate("text", x = -Inf, y = md.mpg, label = sprintf("md = %.1f", md.mpg), vjust = -1.2, hjust = -0.2) +
  geom_hline(yintercept = 25,linetype = 8) +
  annotate("text", x = -Inf, y = 25, label = "value = 25", vjust = -1.2, hjust = -0.2)

In your example above, you have no different linetypes, at least none that are mapped to the data, so what kind of legend are you looking for?

Daniel
  • 7,252
  • 6
  • 26
  • 38
  • Yes, and post this I wanted to add the legend pertaining to the 'ablines': one at median and the other at a particular value – Ayan Nov 11 '14 at 07:21
  • I'm still not sure whether you are looking for another legend, or simply an annotation. See my edited example above. If you really want to add a legend for the line types, use `scale_linetype`. But you have to map your line type values to the data, i.e. they must appear in the data frame and `linetype` will be a parameter of `aes`. – Daniel Nov 11 '14 at 08:22
  • Wow...this looks cool. Thanks! I thought the legend for gears didn't make much sense so I thought of having the abline types as an alternative legend, but upon seeing the annotation, they look meaningful. I had no clue about the annotation too. – Ayan Nov 11 '14 at 10:13