I need the half-violins on the outside, so i need to spread them away from their 'x' positions. And i want the geom_points on the inside (between 'a' and 'b' slightly).
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:
Thanks.
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.