【问题标题】:Split violin plot with ggplot2用ggplot2分割小提琴图
【发布时间】:2016-06-13 13:01:48
【问题描述】:

我想使用 ggplot 创建一个分割小提琴密度图,就像 seaborn 文档的 this page 上的第四个示例一样。

这是一些数据:

set.seed(20160229)

my_data = data.frame(
    y=c(rnorm(1000), rnorm(1000, 0.5), rnorm(1000, 1), rnorm(1000, 1.5)),
    x=c(rep('a', 2000), rep('b', 2000)),
    m=c(rep('i', 1000), rep('j', 2000), rep('i', 1000))
)

我可以像这样绘制躲避的小提琴:

library('ggplot2')

ggplot(my_data, aes(x, y, fill=m)) +
  geom_violin()

但很难直观地比较并排分布中不同点的宽度。我无法在 ggplot 中找到任何拆分小提琴的示例 - 有可能吗?

我找到了base R graphics solution,但该函数很长,我想突出显示分布模式,这些分布模式很容易在 ggplot 中作为附加层添加,但如果我需要弄清楚如何编辑该函数,将很难做到.

【问题讨论】:

    标签: r ggplot2 violin-plot ggproto


    【解决方案1】:

    注意:我认为 jan-glx 的答案要好得多,大多数人应该改用它。但有时,手动方法仍然有助于做一些奇怪的事情。


    您可以通过事先自己计算密度,然后绘制多边形来实现这一点。请参阅下面的粗略想法。

    获取密度

    library(dplyr)
    pdat <- my_data %>%
      group_by(x, m) %>%
      do(data.frame(loc = density(.$y)$x,
                    dens = density(.$y)$y))
    

    组的翻转和偏移密度

    pdat$dens <- ifelse(pdat$m == 'i', pdat$dens * -1, pdat$dens)
    pdat$dens <- ifelse(pdat$x == 'b', pdat$dens + 1, pdat$dens)
    

    情节

    ggplot(pdat, aes(dens, loc, fill = m, group = interaction(m, x))) + 
      geom_polygon() +
      scale_x_continuous(breaks = 0:1, labels = c('a', 'b')) +
      ylab('density') +
      theme_minimal() +
      theme(axis.title.x = element_blank())
    

    结果

    【讨论】:

    • 如果有这些组(例如 i、j 和 x),你将如何计算密度
    • 三组情节应该是什么样的?如果您想显示每把小提琴中所有三个组的密度曲线,可能很难形象化。
    • 对于原始数据庞大的情况,这是一个很好的选择。预先计算的密度使情节更加轻巧!
    • 太棒了!!我设法让你的方法与 plotnine 一起工作。我想使用 plotnine 而不是 seaborn 来提供与其他图表一致的感觉,而第一个解决方案看起来很难实现。你很容易。很棒的解决方案!
    【解决方案2】:

    或者,为了避免摆弄密度,您可以像这样扩展ggplot2's GeomViolin

    GeomSplitViolin <- ggproto("GeomSplitViolin", GeomViolin, 
                               draw_group = function(self, data, ..., draw_quantiles = NULL) {
      data <- transform(data, xminv = x - violinwidth * (x - xmin), xmaxv = x + violinwidth * (xmax - x))
      grp <- data[1, "group"]
      newdata <- plyr::arrange(transform(data, x = if (grp %% 2 == 1) xminv else xmaxv), if (grp %% 2 == 1) y else -y)
      newdata <- rbind(newdata[1, ], newdata, newdata[nrow(newdata), ], newdata[1, ])
      newdata[c(1, nrow(newdata) - 1, nrow(newdata)), "x"] <- round(newdata[1, "x"])
    
      if (length(draw_quantiles) > 0 & !scales::zero_range(range(data$y))) {
        stopifnot(all(draw_quantiles >= 0), all(draw_quantiles <=
          1))
        quantiles <- ggplot2:::create_quantile_segment_frame(data, draw_quantiles)
        aesthetics <- data[rep(1, nrow(quantiles)), setdiff(names(data), c("x", "y")), drop = FALSE]
        aesthetics$alpha <- rep(1, nrow(quantiles))
        both <- cbind(quantiles, aesthetics)
        quantile_grob <- GeomPath$draw_panel(both, ...)
        ggplot2:::ggname("geom_split_violin", grid::grobTree(GeomPolygon$draw_panel(newdata, ...), quantile_grob))
      }
      else {
        ggplot2:::ggname("geom_split_violin", GeomPolygon$draw_panel(newdata, ...))
      }
    })
    
    geom_split_violin <- function(mapping = NULL, data = NULL, stat = "ydensity", position = "identity", ..., 
                                  draw_quantiles = NULL, trim = TRUE, scale = "area", na.rm = FALSE, 
                                  show.legend = NA, inherit.aes = TRUE) {
      layer(data = data, mapping = mapping, stat = stat, geom = GeomSplitViolin, 
            position = position, show.legend = show.legend, inherit.aes = inherit.aes, 
            params = list(trim = trim, scale = scale, draw_quantiles = draw_quantiles, na.rm = na.rm, ...))
    }
    

    并像这样使用新的geom_split_violin

    ggplot(my_data, aes(x, y, fill = m)) + geom_split_violin()
    

    【讨论】:

    • 如果我想要组“a”和“b”的不同颜色怎么办?谢谢!
    • @user3236841 不确定在哪种情况下这是可取的,但由于它是用模数实现的,它可能已经工作了?您是否尝试在因子 m 中使用 4 个级别?如果你只有两个级别,你可以使用:ggplot(my_data, aes(x, y, fill=interaction(x,m))) + geom_split_violin() 来获得不同的颜色,我想。
    • 是的,确实,这行得通!谢谢。当 a 和 b 的分布是不同的东西时很有用,并且分布是标准化的,也许。
    • 另请参阅here,了解有关基于此函数在分割小提琴上绘制分位数的一些主要工作代码。
    • 我认为这是一个很棒的功能。但是,我更喜欢使用 @Axeman 的解决方案,因为它返回一个连续的 x 轴。我确信也有一种方法可以在您的几何图形中使用底层(连续)密度分布,但这对我来说并不直接。
    猜你喜欢
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 2018-12-16
    • 2019-01-21
    • 2019-12-18
    相关资源
    最近更新 更多