使用 ggplotly 对箱线图进行分组时不遵守分组

Grouping not respected when using ggplotly to group boxplots

我正在尝试使用以下代码,以便使用 ggplot2 获得根据不同类别分组的箱线图:

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

我在 Whosebug 中对 post 图片还是太菜鸟了,但是 this is the result I want.

但是,当我尝试使用

将其转换为 plotly 时
pp <- ggplotly(p)
pp

最后 2 个分组层(形状和颜色)是 "ignored" 并且所有箱线图都绘制在彼此之上,仅尊重 aes(x = category_1, ...) 中指定的 x 轴分组see here.

如何避免这个问题?感谢您的宝贵时间。

编辑

我尝试直接使用 plotly 语法,使用以下代码得到了类似的结果:

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. 我说类似是因为 plotly 强制点在箱线图旁边,而不是在箱线图之上,这不是我想要的。

我猜问题是"solved"。虽然,我仍然很好奇上面的问题是否有解释。再次感谢!

我想这会解决你的问题。

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

干杯。