【问题标题】:Grouping not respected when using ggplotly to group boxplots使用 ggplotly 对箱线图进行分组时不考虑分组
【发布时间】:2020-01-31 15:33:31
【问题描述】:

我正在尝试使用以下代码来获取带有 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

我在 stackoverflow 中仍然太菜鸟,无法发布图片,但是 this is the result I want.

但是,当我尝试使用

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

最后 2 个分组层(形状和颜色)被“忽略”,所有箱线图都绘制在彼此的顶部,只尊重 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 强制点在箱线图旁边,而不是在箱线图的顶部,这不是我想要的。

我猜这个问题已经“解决”了。虽然,我仍然很好奇上述问题是否有解释。再次感谢!

【问题讨论】:

    标签: r ggplot2 plotly boxplot ggplotly


    【解决方案1】:

    我认为这将解决您的问题。

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

    干杯。

    【讨论】:

      猜你喜欢
      • 2013-04-19
      • 1970-01-01
      • 2013-08-28
      • 2021-07-31
      • 2014-12-13
      • 2020-05-22
      • 2021-08-28
      • 2014-10-06
      • 1970-01-01
      相关资源
      最近更新 更多