使用 R plotly 中的标记将抖动添加到分组箱线图

Add jitter to grouped box plot using markers in R plotly

我想要 interactive(这意味着它们可以通过 box/lasso 选择)抖动点显示在 分组箱线图 上。我是从这个问题出来的:。我想要完全一样,但箱线图应该分组。

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

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

当我尝试按因子对 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")

当我尝试在 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")

有什么想法吗?


boxpoints 适合你吗? See this
您可以通过 pointpos 参数移动这些点。

iris %>% 
  plot_ly(x = ~cut( Sepal.Length, breaks = 4), 
          y = ~Petal.Width, 
          color = ~Species, 
          type = "box",
          marker = list( size = 10),
          boxpoints = "all",
          jitter = 0.4,
          pointpos = 0,
          hoverinfo = "all"
  ) %>% layout( boxmode = "group")

您可以创建一个 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')