Introduction

This document demonstrates different ways of generating box plots with the base, lattice and ggplot2 plotting packages. Plots make use of the diamonds dataset from the ggplot2 package.

library(knitr)
library(ggplot2)
library(RColorBrewer)
knitr::opts_chunk$set(tidy=T, 
               fig.width=5,
               fig.height=5,
               fig.align='left',
               warning=FALSE,
               message=FALSE,
               echo=TRUE)
options(width = 120)
data(diamonds)
attach(diamonds)

Base Plotting Package

boxplot(price ~ color,
        main="Diamond Prices by Color",
        ylab="Color",
        xlab="Price",
        col=brewer.pal(8,"Pastel2"),
        notch=T,
        horizontal=T)

Lattice Plotting Package

library(lattice)
bwplot(~ price | color,
       main="Diamond Prices by Color",
       ylab="Color",
       xlab="Price",
       horizontal=T,
       layout=c(1,7),
       col="purple")

ggplot2 Plotting Package

ggplot(diamonds, aes(x=color, y=price, colour=color)) +
  geom_boxplot() +
  xlab("Color") +
  ylab("Price") +
  ggtitle("Diamond Prices by Color") +
  theme_bw()

ggplot(diamonds, aes(x=color, y=price, fill=color)) +
  geom_boxplot() +
  xlab("Color") +
  ylab("Price") +
  ggtitle("Diamond Prices by Color") +
  coord_flip() +
  scale_fill_brewer(palette="Pastel1") +
  theme_bw()

Programming Environment

sessionInfo()
## R version 3.3.3 (2017-03-06)
## Platform: x86_64-apple-darwin13.4.0 (64-bit)
## Running under: macOS Sierra 10.12.3
## 
## locale:
## [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] lattice_0.20-35    RColorBrewer_1.1-2 ggplot2_2.2.1      knitr_1.15.1      
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_0.12.10     digest_0.6.12    rprojroot_1.2    plyr_1.8.4       grid_3.3.3       gtable_0.2.0    
##  [7] backports_1.0.5  formatR_1.4      magrittr_1.5     evaluate_0.10    scales_0.4.1     stringi_1.1.3   
## [13] lazyeval_0.2.0   rmarkdown_1.4    labeling_0.3     tools_3.3.3      stringr_1.2.0    munsell_0.4.3   
## [19] yaml_2.1.14      colorspace_1.3-2 htmltools_0.3.5  tibble_1.3.0