[英]How do I move a half-violin plot (outside), a boxplot (middle), and geom_points (inside) for each categorical variable on the x-axis? ggplot2, R
I need the half-violins on the outside, so i need to spread them away from their 'x' positions.我需要外面的半小提琴,所以我需要把它们从它们的“x”位置散开。 And i want the geom_points on the inside (between 'a' and 'b' slightly).
我想要内部的geom_points(稍微在'a'和'b'之间)。
This:这个:
df1 <- data.frame(ID = 1:12,
var1 = c('a', 'b', 'b', 'a', 'b', 'b', 'a', 'b', 'b', 'a', 'b', 'a'),
var2 = c(16, 11, 14, 19, 14.5, 15, 13, 10, 21, 15, 17, 10))
ggplot(df1, aes(var1, var2)) +
geom_violinhalf(mapping = aes(fill = var2),flip = c(1, 3)) +
geom_boxplot(alpha = 1, width=0.1) +
geom_point()
gives me the following, where everything is stacked on the x-axis:给了我以下,所有东西都堆叠在 x 轴上:
Thanks.谢谢。
One option would be to make use of position_nudge
to shift the x positions of the geom layers.一种选择是使用
position_nudge
来移动几何图层的 x 位置。
However, as you want to shift the layers for your categories in opposite directions you have to split you dataset by categories and the layers separately for each category.但是,当您想要将类别的图层向相反方向移动时,您必须按类别拆分数据集,并为每个类别分别拆分图层。 To this end I make use of helper plotting function and
purrr::map
to loop over the splitted dataframe:为此,我使用辅助绘图 function 和
purrr::map
循环分割的 dataframe:
library(ggplot2)
library(see)
ggplot(mapping = aes(var1, var2)) +
purrr::imap(split(df1, df1$var1), function(x, y) {
# Shift in which direction?
fac <- if (y == "a") 1 else -1
# Flip half violin in which direction?
flip <- y == "a"
list(
geom_violinhalf(data = x, mapping = aes(fill = var2), flip = flip, position = position_nudge(x = -.25 * fac)),
geom_boxplot(data = x, alpha = 1, width=0.1),
geom_point(data = x, position = position_nudge(x = .25 * fac))
)
}) +
scale_x_discrete(expand = c(0, .8))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.