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
Solution 1:
One option would be to make use of position_nudge
to shift the x positions of the geom layers.
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:
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))