我正在准备一个盒子图,它应该同时显示boxplot和datapoints。数据点应该在右侧轻推,而箱图应该在左侧。
我使用R-Package ggbeeswarm的geom_beeswarm函数来避免重叠点,类似于geom_jitter。
但是,因为我想在左侧添加一个箱线图,我想将数据点水平向右移动,以便左侧有空间用于箱线图。
我尝试过使用position = position_nudge(x = 0.5),但geom_beeswarm的参数未知。 nudge_x = 0.5也是如此。
有人有另一个解决方案将geom_beeswarm图移到右边吗?
df <- data.frame('variable'=rep(c('control','treatment'),each=20),
'value'=c(runif(20, min=0, max=3), rnorm(60)))
ggtest<-ggplot(df,aes(variable, value)) +
geom_beeswarm(priority='random',cex=2.5)
ggtest
尝试这个。基本上首先创建一个新的变量,它是你的"variable"
的副本,只需使用paste0
添加一个数字,以避免混淆,我将其命名为"variable2"
。
打印新的df
以查看差异。这个新的variable2
将被用作aes()
的geom_beeswarm()
,然后只需使用scale_x_discrete
并与theme()
一起玩,将文本置于x-axis
的中心。
我再次建议在调用qazxsw poi ecc之前打印该情节,看看我的意思。
scale_x_discrete()
df$variable2 <- paste0(df$variable, "2") # create a second almost identical variable
ggplot(df,aes(variable, value)) +
geom_beeswarm(aes(variable2),priority='random',cex=2.5) + # use variable2 as custom aes() for the bees
geom_boxplot() +
# play with this to customize labels, we just want to hide "control2" and "treatment2"
scale_x_discrete(breaks = c("control", "treatment")) +
# with this we center the text and remove the tick marks to improve the plot
theme(axis.text.x = element_text(hjust=-1),
axis.ticks.x = element_blank(),
panel.grid.major.x = element_blank()) # removes vertical grid white lines
数据示例:
更新以回答更多间距的OP请求。
我找不到更好的方法来增加library(ggbeeswarm)
df <- data.frame('variable'=rep(c('control','treatment'),each=20),
'value'=c(runif(20, min=0, max=3), rnorm(60)))
之间的间距。我使用了创建两个虚拟新变量的技巧,这些变量将用于在geoms
旁边绘制第三个geom
。
这将迫使beeswarm
做出一些间距,并且通过设置与ggplot
的geom
相同的color
来隐藏新的bg
。
我用过panel
。
新示例数据:
geom_boxplot()
创建两个新变量,我们可以用它来绘制第三个对象,它将使用与df <- data.frame('variable'=rep(letters[1:7],each=20),
'value'=c(runif(40, min=0, max=3), rnorm(100)))
df$variable2 <- paste0(df$variable, "2") # create a second almost identical variable
相同的color
进行掩码。
bg
最后:
df$variable3 <- paste0(df$variable, "3")
df$value3 <- c(runif(40, min=0, max=3), rnorm(100))
ggplot(df,aes(variable, value)) +
geom_beeswarm(aes(variable2),priority='random',cex=2.5) +
geom_boxplot() +
geom_boxplot(aes(variable3, value3), color="white") + # this is the boxplot that we will hide (notice the color choice)
scale_x_discrete(breaks = c(letters[1:7])) +
theme(axis.text.x = element_text(hjust=-6), # adjust to center the x-labels
axis.ticks.x = element_blank(),
panel.background = element_rect(color="white", fill="white"),
panel.grid.major.x = element_blank(),
panel.grid.major = element_blank(), # to remove grid lines
panel.grid.minor = element_blank(),
axis.line = element_line(size = 0.5, linetype = "solid",
colour = "black"))
再次,这可以进一步调整。