默认情况下,如果最宽点出现在相同高度,相邻小提琴将在最宽点处相互接触。我想让我的小提琴图更宽,以便它们相互重叠。基本上,更类似于山脊情节:
这可以用geom_violin
吗?
我看到width
参数,但如果我将其设置为高于1,我会收到这些警告,这让我认为这可能不是最合适的方法:
Warning: position_dodge requires non-overlapping x intervals
答案 0 :(得分:3)
我不认为geom_violin
是通过设计来实现的,但我们可以通过一些努力来破解它。
使用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
)