首页 文章

ggplot2箱图中的alpha和填充图例?

提问于
浏览
5

我正在尝试将alpha和填充ggplot2结合起来 . 当我使用geom_bar(或geom_points,用于颜色)时它可以工作,但是当我使用geom_boxplot时,alpha图例不起作用 .

library(data.table)
library(ggplot2)
dt = data.table(x = rep(1:5,6), y = rnorm(30), tag1 = rep(c('hey', 'what'), 15), tag2 = rep(c('yeah', 'yeah', 'so', 'so', 'so'), 6))

它适用于酒吧:

ggplot(dt[, list(y=mean(y)), by=list(x, tag1, tag2)], aes(x=x, y=y, fill=tag1, alpha=tag2, group=interaction(x,tag1,tag2))) + geom_bar(stat = 'identity', position = 'dodge')

enter image description here

但不是boxplot - alpha图例是空的 .

ggplot(dt, aes(x=x, y=y, fill=tag1, alpha=tag2, group=interaction(x,tag1,tag2))) + geom_boxplot()

enter image description here

更简单的版本可以在没有填充的情况下完成 - 看起来条形图默认为灰色/浅灰色,而boxplot默认为白色/浅白色:

ggplot(dt[, list(y=mean(y)), by=list(x, tag2)], aes(x=x, y=y, alpha=tag2, group=interaction(x,tag2))) + geom_bar(stat = 'identity')

enter image description here

ggplot(dt, aes(x=x, y=y, alpha=tag2, group=interaction(x,tag2))) + geom_boxplot()

enter image description here

但我真的不确定如何解决这个问题..有什么想法吗?

1 回答

  • 4

    我实际上在箱形图的图例中提供了alpha级别,但您可以使用 override.aes 对其进行硬编码 . (编者注:我发现对于箱形图或条形图而言,alpha美学有点令人困惑 . 难以在心理上将透明度与填充色分开,灰度alpha图例会加剧问题,因为没有任何内容映射到灰色剧情 . )

    在下面的代码中,为了提高图例的可见性,我删除了 alpha 图例中的框线并增加了图例键高度 . 我还编辑了美学,以消除对 group 论证的需要 .

    ggplot(dt, aes(x=factor(x), y=y, fill=tag1, alpha=tag2)) + 
      geom_boxplot() +
      scale_alpha_manual(values=c(0.2,0.7)) +
      guides(alpha=guide_legend(override.aes=list(fill=hcl(c(15,195),100,0,alpha=c(0.2,0.7)),
                                                  colour=NA))) +
      theme(legend.key.height=unit(1,"cm"))
    

    enter image description here

    另一种选择是将 interaction 用于填充和alpha美学,但事实证明ggplot在这种情况下不包含任何颜色:

    ggplot(dt, aes(x=factor(x), y=y, alpha=interaction(tag1,tag2)), 
           fill=interaction(tag1,tag2)) + 
      geom_boxplot() +
      scale_fill_manual(values=rep(hcl(c(15,195),100,65), 2)) +
      scale_alpha_manual(values=rep(c(0.3, 1), each=2)) +
      theme(legend.key.height=unit(2,"cm"))
    

    enter image description here

    因此,您可以使用填充美学来完成所有操作,但在颜色规范中包含透明度 . 这是有效的,但是,再次,因为透明度和颜色在视觉感知上有些混合,所以最好只选择四种不同的颜色 .

    ggplot(dt, aes(x=factor(x), y=y, fill=interaction(tag1,tag2,sep="-"))) + 
      geom_boxplot() +
      scale_fill_manual(values=hcl(c(15,195,15,195),100,65, alpha=c(0.4,0.4,1,1))) +
      theme(legend.key.height=unit(1,"cm")) +
      labs(fill="Tag 1 - Tag 2")
    

    enter image description here

相关问题