简体   繁体   中英

Legends of linetypes

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM