Я не думаю, что geom_violin
предназначен для этого, но мы можем взломать его с некоторым усилием.
Иллюстрация с использованием набора данных diamonds из ggplot2:
# normal violin plot
p1 <- diamonds %>%
ggplot(aes(color, depth)) +
geom_violin()
# overlapping violin plot
p2 <- diamonds %>%
rename(x.label = color) %>% # rename the x-variable here;
# rest of the code need not be changed
mutate(x = as.numeric(factor(x.label)) / 2) %>%
ggplot(aes(x = x, y = depth, group = x)) +
# plot violins in two separate layers, such that neighbouring x values are
# never plotted in the same layer & there's no overlap WITHIN each layer
geom_violin(data = . %>% filter(x %% 1 != 0)) +
geom_violin(data = . %>% filter(x %% 1 == 0)) +
# add label for each violin near the bottom of the chart
geom_text(aes(y = min(depth), label = x.label), vjust = 2, check_overlap = TRUE) +
# hide x-axis labels as they are irrelevant now
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank())
gridExtra::grid.arrange(
p1 + ggtitle("Normal violins"),
p2 + ggtitle("Overlapping violins"),
nrow = 2
)