2

默认情况下,如果最宽点出现在同一高度,则相邻小提琴将在最宽点处相互接触。我想让我的小提琴图更宽,以便它们相互重叠。基本上,更类似于山脊图:

岭图

这可能geom_violin吗?

我看到了这个width参数,但是如果我将它设置为高于 1,我会收到这些警告,这让我认为这可能不是最合适的方法:

Warning: position_dodge requires non-overlapping x intervals
4

1 回答 1

3

我不认为geom_violin它是有意设计的,但我们可以通过一些努力来破解它。

使用 ggplot2 中的 diamonds 数据集进行说明:

# 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
)

阴谋

于 2018-06-08T01:59:44.057 回答