Black Lives Matter. Please consider donating to Black Girls Code today.
https://www.blackgirlscode.com/

geom_boxplot in ggplot2

How to make a box plot in ggplot2. Examples of box plots in R that are grouped, colored, and display the underlying data distribution.


New to Plotly?

Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

Basic Boxplot

library(plotly)

set.seed(1234)
dat <- data.frame(cond = factor(rep(c("A","B"), each=200)), rating = c(rnorm(200),rnorm(200, mean=.8)))

p <- ggplot(dat, aes(x=cond, y=rating)) + geom_boxplot()

fig <- ggplotly(p)

fig

Colored Boxplot

library(plotly)

set.seed(1234)
dat <- data.frame(cond = factor(rep(c("A","B"), each=200)), rating = c(rnorm(200),rnorm(200, mean=.8)))

p <- ggplot(dat, aes(x=cond, y=rating, fill=cond)) + geom_boxplot()

fig <- ggplotly(p)

fig

Flipped Boxplot

library(plotly)

set.seed(1234)
dat <- data.frame(cond = factor(rep(c("A","B"), each=200)), rating = c(rnorm(200),rnorm(200, mean=.8)))

p <- ggplot(dat, aes(x=cond, y=rating, fill=cond)) + geom_boxplot() +
    guides(fill=FALSE) + coord_flip()

fig <- ggplotly(p)

fig

Boxplot w/ Stats

library(plotly)

set.seed(1234)
dat <- data.frame(cond = factor(rep(c("A","B"), each=200)), rating = c(rnorm(200),rnorm(200, mean=.8)))

p <- ggplot(dat, aes(x=cond, y=rating)) + geom_boxplot() +
    stat_summary(fun.y=mean, geom="point", shape=5, size=4)

fig <- ggplotly(p)

fig

Boxplot Facets

library(plyr)
library(reshape2)
library(plotly)

set.seed(1234)
x<- rnorm(100)
y.1<-rnorm(100)
y.2<-rnorm(100)
y.3<-rnorm(100)
y.4<-rnorm(100)

df<- (as.data.frame(cbind(x,y.1,y.2,y.3,y.4)))

dfmelt<-melt(df, measure.vars = 2:5)

p <- ggplot(dfmelt, aes(x=factor(round_any(x,0.5)), y=value,fill=variable))+
    geom_boxplot()+
    facet_grid(.~variable)+
    labs(x="X (binned)")+
    theme(axis.text.x=element_text(angle=-90, vjust=0.4,hjust=1))

fig <- ggplotly(p)

fig

Time Series Facets

library(foreign)
library(MASS)
library(Hmisc)
library(reshape2)
library(plotly)

dat <- read.dta("https://stats.idre.ucla.edu/stat/data/ologit.dta")
invisible(lapply(dat[, c("apply", "pared", "public")], table))
invisible(ftable(xtabs(~ public + apply + pared, data = dat)))

p <- ggplot(dat, aes(x = apply, y = gpa)) +
    geom_boxplot(size = .75) +
    facet_grid(pared ~ public, margins = TRUE)

fig <- ggplotly(p)

fig

Outliers

library(plotly)
set.seed(123)

df <- diamonds[sample(1:nrow(diamonds), size = 1000),]

p <- ggplot(df, aes(cut, price, fill = cut)) + 
  geom_boxplot(outlier.shape = NA) + 
  ggtitle("Ignore outliers in ggplot2")

# Need to modify the plotly object and make outlier points have opacity equal to 0
fig <- plotly_build(p)

fig$data <- lapply(fig$data, FUN = function(x){
  x$marker = list(opacity = 0)
  return(x)
})

fig

Linewidth

library(plotly)
set.seed(123)

df <- diamonds[sample(1:nrow(diamonds), size = 1000),]

p <- ggplot(df, aes(cut, price, fill = cut)) + 
  geom_boxplot(size = 1) + 
  ggtitle("Adjust line width of boxplot in ggplot2")

# Need to modify the plotly object to make sure line width is larger than default
fig <- plotly_build(p)

fig$data <- lapply(fig$data, FUN = function(x){
  x$line = list(width = 10)
  return(x)
})

fig

Whiskers

library(plotly)
set.seed(123)

df <- diamonds[sample(1:nrow(diamonds), size = 1000),]

# This is how it needs to be done in ggplot
p <- ggplot(df, aes(color, price)) +
  stat_boxplot(geom ='errorbar') + 
  geom_boxplot()+
  ggtitle("Add horizontal lines to whiskers using ggplot2")

# Note that plotly will automatically add horozontal lines to the whiskers
p <- ggplot(df, aes(cut, price, fill = cut)) +
  geom_boxplot()+
  ggtitle("Add horizontal lines to whiskers using ggplot2")

fig <- ggplotly(p)

fig

These example were inspired by Cookbook for R.

What About Dash?

Dash for R is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash for R at https://dashr.plot.ly/installation.

Everywhere in this page that you see fig, you can display the same figure in a Dash for R application by passing it to the figure argument of the Graph component from the built-in dashCoreComponents package like this:

library(plotly)

fig <- plot_ly() 
# fig <- fig %>% add_trace( ... )
# fig <- fig %>% layout( ... ) 

library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)

app <- Dash$new()
app$layout(
    htmlDiv(
        list(
            dccGraph(figure=fig) 
        )
     )
)

app$run_server(debug=TRUE, dev_tools_hot_reload=FALSE)