我如何按组拆分一个令人不快的情节,类似于:Split violin plot with ggplot2
但是我想获得积分而不是密度图......
"计算密度方法"正如@axeman在链接问题中所建议的那样显然不起作用,因为这种情况不会使用密度。
#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'
代替笑脸&#39;。看到
Split beeswarm 2。
答案 0 :(得分:5)
您可以尝试使用硬编码解决方案
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)