4

I have a regular boxplot in ggplot2:

# working example
library(ggplot2)

mtcars %>%
  mutate(cyl=as.factor(cyl)) %>%
  mutate(vs=as.factor(vs)) %>%

  ggplot(aes(y=mpg, x=cyl)) +
  geom_boxplot(aes(colour=vs))

It looks like this: enter image description here

However, when I create an object and pass it to plotly, I lose the dodge position:

library(plotly)
mtcars_boxplot <-
mtcars %>%
  mutate(cyl=as.factor(cyl)) %>%
  mutate(vs=as.factor(vs)) %>%

  ggplot(aes(y=mpg, x=cyl)) +
  geom_boxplot(aes(colour=vs))

mtcars_boxplot %>%
  ggplotly() 

It looks like this: enter image description here

I tried to add position=position_dodge() & position=position_dodge2() but none of them worked:

library(plotly)

mtcars_boxplot <-
mtcars %>%
  mutate(cyl=as.factor(cyl)) %>%
  mutate(vs=as.factor(vs)) %>%

  ggplot(aes(y=mpg, x=cyl)) +
  geom_boxplot(aes(colour=vs), position=position_dodge2())

mtcars_boxplot %>%
  ggplotly() 

What should I do to keep the dodge position like the first plot?

ashwin agrawal
  • 1,603
  • 8
  • 16
Hamideh
  • 665
  • 2
  • 8
  • 20

1 Answers1

11

As suggested here, add layout(boxmode = "group")

library(plotly)
mtcars_boxplot %>%
  ggplotly() %>%
  layout(boxmode = "group")
A. Suliman
  • 12,923
  • 5
  • 24
  • 37
  • This kind of works for me (prints out side by side boxes) but, I get a warning ``'layout' objects don't have these attributes: 'boxmode'`. The box width also becomes quite narrow. – steveb Feb 01 '20 at 00:34
  • @steveb the warning should be fine as they mentioned [here](https://github.com/ropensci/plotly/issues/994). The box width should become narrower to account for the missing level in _cyl=8_ which is the desired behavior in this case, actually `plotly` handles this better than `ggplot2` see [here](https://github.com/tidyverse/ggplot2/issues/3345)" – A. Suliman Feb 01 '20 at 11:12
  • 1
    I forgot to mention, I was plotting my own data and have had an issue with the box width when using `ggplotly`, however, when I just use `ggplot` or `plotly` (directly, not with `ggplotly`), I don't have the box width issue. I may need to create a new SO question if I am to get an answer. I need to do some experimenting on my particular issue before posting. – steveb Feb 02 '20 at 05:59
  • The issue I am running into is happening when I put my 6 plots into a 3x2 subplot. This doesn't happen in straight `ggplot` but it does happen when using `plotly`. – steveb Feb 02 '20 at 06:29
  • Has there been a solution to solve the with issue yet? I am still experiencing it. – ktm Aug 04 '22 at 16:54