分割蜂群图 [英] Split beeswarm plot

查看:115
本文介绍了分割蜂群图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何按组划分蜂群图,类似于此:用ggplot2划分小提琴图

How can I split a beeswarm plot by group, similar to this: Split violin plot with ggplot2

但是我想获得点数而不是密度图...

But instead of density plots, I would like to get points...

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

The "calculating the density approach" as suggested by @axeman in the linked question does obviously not work, because beeswarm doesn't use densities.

#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')

所需的输出类似:

  • 使用 Adob​​e illustrator 编辑结果图,以显示 我想得到...
  • 中心轴上的点应该是 视组而定,也向左/向右躲避.
  • The resulting plot was edited with Adobe illustrator, in order to show what I want to get...
  • The points in the central axis should rather be dodged to the left/right too, depending on the group.

编辑
实现我想要的更好的方法是使用method = 'pseudorandom'而不是'smiley'.请参阅
拆分蜂群2 .

Edit
a better way to achieve what I want is to use method = 'pseudorandom' instead of 'smiley'. see
Split beeswarm 2.

推荐答案

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

You can try following hardcoded solution

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

以更通用的方式进行操作,您可以创建一个用于按组切换x调整的函数

Doing it in a more generalized way, you can create a function for switching x-adjustment per group

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

和更新的图

foo(p)

这篇关于分割蜂群图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆