使用 plotly 中的标记向箱线图添加抖动

Add jitter to box plot using markers in plotly

我做了一个箱线图:

dat %>%
  plot_ly(y = ~xval, color = ~get(col), type = "box", 
          boxpoints = "all", jitter = 0.7,
          pointpos = 0, marker = list(size = 3),
          source = shiny_source, key = shiny_key,
          hoverinfo = 'text', text = txt)

但问题是抖动的点不是交互式的,不能单独标记,所以我想到了使用 add_markers:

添加这些点的想法
dat %>%
  plot_ly(y = ~xval, color = ~get(col), type = "box", 
          boxpoints = FALSE, jitter = 0.7,
          pointpos = 0, marker = list(size = 3),
          source = shiny_source, key = shiny_key,
          hoverinfo = 'col', text = txt
  ) %>%
  add_markers(x = ~get(col), y = ~varval, size = I(6))

但现在点在直线上,我想添加一些抖动(例如通过使用 beeswarm 包)。但我不知道如何获取 X 轴上定性变量 IC0 的坐标。有什么想法吗?

我发现自己经常使用 plotly 和 ggplot2 处于相同的潜在案例中——3 行代码即可获得我想要的 90%,而 30 行代码可获得美观 just对。

一个潜力 solution/workaround:利用 R 的 "factors are coded with integers" 范例,以数字标度绘制所有内容,然后通过隐藏 x 个标签和 x 个悬停值来覆盖您的足迹。

dat <- data.frame(xval = sample(100,1000,replace = TRUE),
                  group = as.factor(sample(c("a","b","c"),1000,replace = TRUE)))

dat %>%
  plot_ly() %>% 
  add_trace(x = ~as.numeric(group),y = ~xval, color = ~group, type = "box", 
            hoverinfo = 'name+y') %>%
  add_markers(x = ~jitter(as.numeric(group)), y = ~xval, color = ~group,
              marker = list(size = 6),
              hoverinfo = "text",
              text = ~paste0("Group: ",group,
                             "<br>xval: ",xval),
              showlegend = FALSE) %>% 
  layout(legend = list(orientation = "h",
                       x =0.5, xanchor = "center",
                       y = 1, yanchor = "bottom"
                       ),
         xaxis = list(title = "Group",
                      showticklabels = FALSE))

产生以下结果