在图中使用标记将抖动添加到框图中

时间:2017-10-20 07:52:33

标签: r plot plotly boxplot jitter

我做了一个箱子图:

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)

enter image description here

但问题是抖动的点不是交互式的,不能单独标记,所以我想到了使用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))

enter image description here

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

1 个答案:

答案 0 :(得分:7)

我发现自己处于相同的潜在案例中,经常使用plotly和ggplot2-- 3行代码来获得我想要的90%,以及30行代码来获得美学只是

一个潜在的解决方案/解决方法:利用R"因子用整数编码"范例,在数字刻度上绘制所有内容,然后通过隐藏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))

产生以下

enter image description here