【问题标题】:Fill specific regions in geom_violin plot填充 geom_violin 图中的特定区域
【发布时间】:2016-03-24 14:55:30
【问题描述】:

如何在 ggplot2 中根据固定的截止值用不同的颜色填充geom_violin 图?

例如,给定设置:

library(ggplot2)

set.seed(123)
dat <- data.frame(x = rep(1:3,each = 100),
                  y = c(rnorm(100,-1),rnorm(100,0),rnorm(100,1)))
dat$f <- with(dat,ifelse(y >= 0,'Above','Below'))

我想采取这个基本情节:

ggplot() + 
    geom_violin(data = dat,aes(x = factor(x),y = y))

并且简单地让每把小提琴在零上下都有不同的颜色。尝试天真的事情,映射fill 美学,分裂和躲避小提琴情节:

ggplot() + 
    geom_violin(data = dat,aes(x = factor(x),y = y, fill = f))

这不是我想要的。我想要在每个 x 值处有一个小提琴图,但内部填充了高于和低于零的不同颜色。

【问题讨论】:

  • 这里有人这样做吗?找到他们认为新的东西……问一个问题,然后回答它……都是为了那些甜蜜的互联网点?
  • @cory 嗯...yes,是的。然而,在 cmets 中粗鲁和居高临下通常是不受欢迎的,你知道的。 (不过,我们都这样做了。)
  • 酷,我不是故意粗鲁的。我只是不知道。我尊重你甜蜜的互联网点。我真的。我为你投了赞成票,所以你会得到更多。

标签: r ggplot2


【解决方案1】:

这是一种方法。

library(ggplot2)
library(plyr)

#Data setup
set.seed(123)
dat <- data.frame(x = rep(1:3,each = 100),
                  y = c(rnorm(100,-1),rnorm(100,0),rnorm(100,1)))

首先,我们将使用ggplot::ggplot_build 来捕获所有用于绘制小提琴图的计算变量:

p <- ggplot() + 
    geom_violin(data = dat,aes(x = factor(x),y = y))
p_build <- ggplot2::ggplot_build(p)$data[[1]]

接下来,如果我们看一下source code 的geom_violin,我们会看到它在将计算的数据帧交给geom_polygon 以绘制小提琴区域的实际轮廓之前对其进行了一些特定的转换。

所以我们将模拟该过程并简单地手动绘制填充的多边形:

#This comes directly from the source of geom_violin
p_build <- transform(p_build,
                     xminv = x - violinwidth * (x - xmin),
                     xmaxv = x + violinwidth * (xmax - x))

p_build <- rbind(plyr::arrange(transform(p_build, x = xminv), y),
                 plyr::arrange(transform(p_build, x = xmaxv), -y))

我从源代码中省略了一个关于复制第一行的小细节,以确保多边形是闭合的。

现在我们做两个最后的修改:

#Add our fill variable
p_build$fill_group <- ifelse(p_build$y >= 0,'Above','Below')
#This is necessary to ensure that instead of trying to draw
# 3 polygons, we're telling ggplot to draw six polygons
p_build$group1 <- with(p_build,interaction(factor(group),factor(fill_group)))

最后是情节:

#Note the use of the group aesthetic here with our computed version,
# group1
p_fill <- ggplot() + 
    geom_polygon(data = p_build,
                 aes(x = x,y = y,group = group1,fill = fill_group))
p_fill

请注意,一般来说,这会破坏对任何分类 x 轴标签的良好处理。因此,您通常需要使用连续的 x 轴进行绘图,然后如果您需要分类标签,请手动添加它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多