Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotly: How to add a median line on a box plot

Tags:

I would like to add trace of a median line on my box plot.

like this

enter image description here

Here are my plots so far:

enter image description here

library(plotly)
p <- plot_ly(y = ~rnorm(50), type = "box") %>%
  add_trace(y = ~rnorm(50, 1))

p
like image 280
Sup'A Avatar asked Feb 06 '20 02:02

Sup'A


1 Answers

Just start out with a scatter plot using plot_ly(..., type='scatter', mode='lines', ...), and follow up with one add_boxplot(...' inherit=FALSE, ...) per box plot. Here's how you do it for an entire data.frame:

enter image description here

Complete code with sample data:

library(dplyr)
library(plotly)

# data
df <- data.frame(iris) %>% select(-c('Species'))
medians <- apply(df,2,median)

# create common x-axis values for median line and boxplots
xVals <- seq(0, length(medians)-1, by=1)

# plotly median line setup
p <- plot_ly(x = xVals, y=medians, type='scatter', mode='lines', name='medians')

# add a trace per box plot
i <- 0
for(col in names(df)){
  p <- p %>% add_boxplot(y = df[[col]], inherit = FALSE, name = col)
  i <- i + 1
}

# manage layout
p <- p %>% layout(xaxis = list(range = c(min(xVals)-1, max(xVals)+1)))
p
like image 153
vestland Avatar answered Oct 02 '22 14:10

vestland