Changing the widths of plotly boxes and/or the space between them

Viewed 167

I have grouped data which I want to plot as a group of box plots using R's plotly package, and control the width of the boxes and/or the space between theme.

Here are the data:

set.seed(1)
df <- data.frame(type = c(rep("t1", 1000), rep("t2", 1000), rep("t3", 1000), rep("t4", 1000), rep("t5", 1000), rep("t6", 1000)),
                 age = rep(c(rep("y", 500),rep("o", 500)), 6),
                 value = rep(c(runif(500, 5, 10), runif(500, 7.5, 12.5)), 6),
                 stringsAsFactors = F)
df$age <- factor(df$age, levels = c("y", "o"), ordered = T)

Following plotly's tutorial this is how I'm plotting it:

library(plotly)
library(dplyr)
plot_ly(x = df$type, y = df$value, name = df$age, color = df$type, type = 'box',showlegend = F) %>%
  layout(yaxis=list(title="Diversity"),boxmode='group')

Which gives: enter image description here

Where the boxes come out too narrow and the space both between boxes of the same type as well as the space between the different types are big.

Any idea how to change the box widths and/or the spaces?

According to this post, in python the boxgap and boxgroupgap control these aspects.

2 Answers

Analogous to the python version, layout parameters as being documented here can be changed as arguments of the function layout:

plot_ly(x = df$type, y = df$value, name = df$age, color = df$type,
  type = "box", showlegend = F) %>%
  layout(yaxis = list(title = "Diversity"),
   boxmode = "group", boxgap = 0, boxgroupgap = 0
  )

One alternative is to use a continuous x-axis. Here with ggplotly instead:

# convert factors to numbers
df$itype <- as.numeric (factor (df$type))
sc <- scale (unique (as.numeric (factor (df$age))))
df$iage <- sc[as.numeric (factor (df$age))] * .3

# plot
gg <- 
  ggplot (df, aes (x=itype+iage, y=value, color=type, group=itype+iage)) + 
  geom_boxplot() + 
  scale_x_continuous(labels = levels (factor (df$type)), breaks = 1:length (levels (factor (df$type)))) +
  labs (x="", y="Diversity")


ggplotly (gg) %>%
  layout(boxgroupgap = 0, boxgap=0)

plot

Related