Álvaro
Álvaro

Reputation: 798

Grouping not respected when using ggplotly to group boxplots

I was trying the following code in order to get a graph of boxplots with ggplot2 which are grouped according to different categories:

category_1 <- rep(LETTERS[1:4], each = 20)
value <- rnorm(length(category_1), mean = 200, sd = 20)
category_2 <- rep(as.factor(c("Good", "Medium", "Bad")), length.out = length(category_1))
category_3 <- rep(as.factor(c("Bright", "Dark")), length.out = length(category_1))
df <- data.frame( category_1, value, category_2, category_3)

p <- ggplot(df, aes(x = category_1, y = value, color = category_2, shape = category_3)) +
  geom_boxplot(alpha = 0.5) +
  geom_point(position=position_jitterdodge(), alpha=0.7)

p

I'm still too noob in stackoverflow to post images, but this is the result I want.

However, when I try to convert it to plotly using

pp <- ggplotly(p)
pp

the last 2 grouping layers (shape and color) are "ignored" and all the boxplots are plotted on top of each other, only respecting the x-axis grouping specified in aes(x = category_1, ...) as you can see here.

How can I avoid this problem? Thanks for your time.

EDIT

I've tried using plotly syntax directly and I get a similar result using the following code:

pp <- plot_ly(df, x = ~category_1, y = ~value, color = ~category_2, 
              mode = "markers", symbol = ~category_3, type = "box", boxpoints = "all") %>%
   layout(boxmode = "group")
pp

Here the result. I said similar because plotly forces the dots to be next to, and not on top of the boxplot, which is not exactly what I wanted.

I guess the question is "solved". Although, I'm still curious if there is an explanation for the problem above. Thanks again!

Upvotes: 4

Views: 943

Answers (1)

J.C.
J.C.

Reputation: 140

I think this will solve your issue.

p <- ggplot(df, aes(x = category_1, y = value, color = category_2, shape = category_3)) +
  geom_boxplot(alpha = 0.5) +
  geom_point(position=position_jitterdodge(), alpha=0.7)

p %>%
  ggplotly() %>%
  layout(boxmode = "group")

Cheers.

Upvotes: 4

Related Questions