r - split 蜂群情节

标签 r ggplot2

如何按组拆分蜂群图,类似于:Split violin plot with ggplot2

但不是密度图,我想得到积分......

@axeman 在链接问题中建议的“计算密度方法”显然不起作用,因为 beeswarm 不使用密度。

#Desired output:
require(ggplot2)
require(ggbeeswarm)
my_dat <- data.frame(x = 'x', m = rep(c('a','b'),100), y = rnorm(200))
ggplot(my_dat, aes(x,y))+ geom_quasirandom(method = 'smiley')

所需的输出类似于:

enter image description here
  • 结果图是用 Adob​​e Illustrator 编辑的,以显示什么
    我想得到...
  • 中心轴上的点应该是
    也向左/向右躲避,具体取决于组。

  • 编辑
    实现我想要的更好的方法是使用 method = 'pseudorandom'而不是“笑脸”。看
    Split beeswarm 2 .

    最佳答案

    您可以尝试以下硬编码解决方案

    library(tidyverse)
    # the plot
    p <- ggplot(my_dat, aes(x,y,color=m))+ 
      geom_quasirandom(method = 'smiley')
    # get the layer_data(p, i = 1L)
    p <- ggplot_build(p)
    # update the layer data
    p$data[[1]] <-   p$data[[1]] %>%
      mutate(x=case_when(
        colour=="#00BFC4" ~ PANEL + abs(PANEL - x),
        TRUE ~ PANEL - abs(PANEL - x))
      )
    # plot the update
    plot(ggplot_gtable(p))
    

    enter image description here

    以更通用的方式进行操作,您可以创建一个用于切换每组 x 调整的函数
    foo <- function(plot){
     p <- ggplot_build(plot)
     p$data[[1]] <-   p$data[[1]] %>%
       mutate(diff = abs(x-round(x)),  # calculating the difference to the x axis position
              # update the new position depending if group is even (+diff) or odd (-diff)
              x = case_when(group %% 2 == 0 ~ round(x) + diff,
                            TRUE ~ round(x) - diff)) %>%
       select(-diff)
     plot(ggplot_gtable(p))
    }
    

    其他一些数据
    set.seed(121)
    p <- diamonds %>% 
      mutate(col=gl(2,n()/2)) %>% 
      sample_n(1000) %>% 
      ggplot(aes(cut,y,color= factor(col)))+ 
      geom_beeswarm()
    p
    

    enter image description here

    和更新的情节
    foo(p)
    

    enter image description here

    关于r - split 蜂群情节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49756005/

    相关文章:

    r - stat_density2d 等高线图图例和点

    r - r 中带有 geom_raster 的热图

    R:什么是NA_character_?

    string - 返回字符串文字的 R 函数

    r - ggplot Complex GridExtra 布局

    r - 使用 ggrepel 标记单个点

    r - 此代码在 R 中生成一条曲线。如何更改此曲线的颜色?

    r - 放大 R - 使用 dynamicTicks 绘图

    r - 如何更改knitr中的目录标题?

    string - 替换字符串中的字符