Box Plots in ggplot2

How to make Box Plots in ggplot2 with Plotly.


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()

ggplotly(p)
Click to copy

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()

ggplotly(p)
Click to copy

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()

ggplotly(p)
Click to copy

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=mean, geom="point", shape=5, size=4)

ggplotly(p)
Click to copy

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))

ggplotly(p)
Click to copy
-2.5-2-1.5-1-0.500.511.522.5-202-2.5-2-1.5-1-0.500.511.522.5-2.5-2-1.5-1-0.500.511.522.5-2.5-2-1.5-1-0.500.511.522.5
variabley.1y.2y.3y.4X (binned)valuey.1y.2y.3y.4

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)

ggplotly(p)
Click to copy
2.02.53.03.54.02.02.53.03.54.0unlikelysomewhat likelyvery likely2.02.53.03.54.0unlikelysomewhat likelyvery likelyunlikelysomewhat likelyvery likely
applygpa01(all)01(all)

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
Click to copy
FairGoodVery GoodPremiumIdeal050001000015000
cutFairGoodVery GoodPremiumIdealIgnore outliers in ggplot2cutprice

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
Click to copy
FairGoodVery GoodPremiumIdeal050001000015000
cutFairGoodVery GoodPremiumIdealAdjust line width of boxplot in ggplot2cutprice

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")

ggplotly(p)
Click to copy
FairGoodVery GoodPremiumIdeal050001000015000
cutFairGoodVery GoodPremiumIdealAdd horizontal lines to whiskers using ggplot2cutprice

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)
Click to copy