使用 R 中的标记向分组箱形图添加抖动

pot*_*kan 5 r boxplot plotly jitter

我希望交互式(这意味着可以通过框/套索选择来选择它们)抖动点显示在分组箱线图上。我提出了这个问题:Add jitter to boxplot usingmarkers inplotly。我想要完全相同,但箱线图应该分组。

我做了一个箱线图,但要点都混淆了:

dat %>%
  plot_ly(x = ~as.numeric(IC), 
            y = ~xval, 
            color = ~gene, 
            type = "box",
            hoverinfo = "none",
            boxpoints = FALSE
          ) %>%
  add_markers(x = ~jitter(as.numeric(IC)),
              y = ~xval,
              color = ~gene,
              marker = list(size = 3),
              hoverinfo = "text",
              text = txt,
              showlegend = TRUE) %>%
layout(boxmode = "group")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

当我尝试按因子对 X 轴进行分组(以便每个组合都是一个级别)时,我无法对箱线图进行分组:

dat <- dat %>% 
  mutate(gene_x_covariate = as.factor(
    paste0(get(facet_title), "-", gene))) 

dat %>%
  plot_ly(x = ~as.numeric(gene_x_covariate), 
            y = ~xval, 
            color = ~gene, 
            type = "box",
            hoverinfo = "none",
            boxpoints = FALSE
          ) %>%
  add_markers(x = ~jitter(as.numeric(gene_x_covariate)),
              y = ~xval,
              color = ~gene,
              marker = list(size = 3),
              hoverinfo = "text",
              text = txt,
              showlegend = TRUE) %>%
layout(boxmode = "group")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

当我尝试混合 X 轴上的变量时,我得到了远离箱线图的点:

dat %>%
  plot_ly(x = ~as.numeric(IC), 
            y = ~xval, 
            color = ~gene, 
            type = "box",
            hoverinfo = "none"
          ) %>%
  add_markers(x = ~jitter(as.numeric(gene_x_covariate)),
              y = ~xval,
              color = ~gene,
              marker = list(size = 3),
              hoverinfo = "text",
              text = txt,
              showlegend = TRUE) %>%
layout(boxmode = "group")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

有任何想法吗?

Pio*_*icz 1

您可以创建一个 ggplot2 对象,然后使用 ggplotly() 函数使其具有交互性。

library(dplyr)
library(ggplot2)
library(plotly)

dat <- data.frame(xval = sample(100,1000,replace = TRUE),
              group1 = as.factor(sample(c("a","b","c"),1000,replace = TRUE)),
              group2 = as.factor(sample(c("g1","g2","g3","g4"),1000, replace = TRUE)))

p <- dat %>% ggplot(aes(x=group2, y=xval, fill=group1)) + 
              geom_boxplot() + geom_jitter() + facet_grid(~group2)

ggplotly(p) %>% layout(boxmode = 'group')
Run Code Online (Sandbox Code Playgroud)