使用R绘图中的标记将抖动添加到分组框图中

时间:2017-11-14 13:20:00

标签: r plotly boxplot jitter

我希望交互式(这意味着可以选择框/套索选项)抖动点显示在分组的boxplot 。我出了这个问题:Add jitter to box plot using markers in plotly。我想要完全相同,但箱图应该分组。

我制作了一个箱形图,但各点都混淆了:

6.10.3

enter image description here

当我尝试将X轴按因子分组时(因此每个组合都是一个级别)我无法将我的箱线图分组:

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

enter image description here

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

enter image description here

有什么想法吗?

2 个答案:

答案 0 :(得分:2)


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

答案 1 :(得分: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')