Cars described by miles per gallon and number of cylinders

Add car type column to mtcars built-in R dataset. Add subgroups of cars based on mpg.

mtcars$type=row.names(mtcars)
mtcars$mpg_breaks=cut(mtcars$mpg,breaks=c(
  0,20,30,40),labels=c("0-20mpg","20-30mpg","30-40mpg"));head(mtcars)
##                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
## Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
## Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
## Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
## Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
## Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
##                                type mpg_breaks
## Mazda RX4                 Mazda RX4   20-30mpg
## Mazda RX4 Wag         Mazda RX4 Wag   20-30mpg
## Datsun 710               Datsun 710   20-30mpg
## Hornet 4 Drive       Hornet 4 Drive   20-30mpg
## Hornet Sportabout Hornet Sportabout    0-20mpg
## Valiant                     Valiant    0-20mpg

Plot car types by mpg and cylinder

library(ggplot2)
q=qplot(type,data=mtcars,geom="bar",weight=mpg,fill=cyl,ylab="MPG",xlab="Car manufacturer and model",main="Cars described by miles per gallon and number of cylinders")
q+facet_wrap(~mpg_breaks, scale="free",ncol=1)+theme(axis.text.x=element_text(angle=90)) 

plot of chunk unnamed-chunk-2