如何按组拆分蜂群图,类似于: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')
所需的输出类似于:
我想得到...
也向左/向右躲避,具体取决于组。
编辑
实现我想要的更好的方法是使用
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))
以更通用的方式进行操作,您可以创建一个用于切换每组 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
和更新的情节
foo(p)
关于r - split 蜂群情节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49756005/