我如何按组分割出一个非常小的情节,类似于:用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')
Run Code Online (Sandbox Code Playgroud)
期望的输出类似于:
编辑
一个更好的方法来实现我想要的是使用method = 'pseudorandom'而不是'笑脸'.见
拆分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))
Run Code Online (Sandbox Code Playgroud)
以更通用的方式执行此操作,您可以创建一个用于切换每组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))
}
Run Code Online (Sandbox Code Playgroud)
其他一些数据
set.seed(121)
p <- diamonds %>%
mutate(col=gl(2,n()/2)) %>%
sample_n(1000) %>%
ggplot(aes(cut,y,color= factor(col)))+
geom_beeswarm()
p
Run Code Online (Sandbox Code Playgroud)
和更新的情节
foo(p)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
564 次 |
| 最近记录: |