【问题标题】:How to use ggplot2's geom_dotplot() with both fill and group如何将 ggplot2 的 geom_dotplot() 与填充和组一起使用
【发布时间】:2015-07-22 08:34:51
【问题描述】:

我真的很喜欢 ggplot2::geom_dotplot() 可以很好地将点堆叠到类别中间的方式,但我似乎无法将它与填充颜色结合起来。

我们来看一个例子:

# test data
tmpData <- data.frame(x=c(rep('x', 3),rep('y', 3)), y=c(1,1,2,1,2,2), fill=rep(c('A', 'B', 'B'), 2))

# Plot without fill color
ggplot(tmpData, aes(x=x, y=y)) + 
    geom_dotplot(binaxis = "y", stackdir = "center", dotsize=4)

导致这个情节:

但是当我添加填充参数时:

ggplot(tmpData, aes(x=x, y=y, fill=fill)) +   
   geom_dotplot(binaxis = "y", stackdir = "center", dotsize=4)

填充似乎覆盖了在“x”上完成的分组,导致两个点 (x, 1)(x, 1) 被折叠我希望它们具有不同的颜色。

当我尝试指定组时,填充颜色被忽略:

ggplot(tmpData, aes(x=x, y=y, group=x, fill=fill)) +
    geom_dotplot(binaxis = "y", stackdir = "center", dotsize=4)

通过启用堆栈组似乎可以避免崩溃:

ggplot(tmpData, aes(x=x, y=y, fill=fill)) +
    geom_dotplot(binaxis = "y", stackgroups=TRUE, stackdir = "center", dotsize=4)

但随后我将数据的中心化为其他 3 个图中的“x”和“y”。

有没有办法将geom_dotplot() 与两个组一起使用并填充?

【问题讨论】:

标签: r ggplot2


【解决方案1】:

如果您愿意接受一些 hacky 解决方案,只是为了让它看起来像您想要的样子...您可以通过简单地为它提供一个颜色名称向量来覆盖填充命令:

tmpData$colorname <- rep(c('red','blue','blue'),2)

ggplot(tmpData, aes(x=x, y=y)) + 
  geom_dotplot(binaxis = "y", stackdir = "center", dotsize=4, fill=tmpData$colorname)

【讨论】:

  • 如何使用这种方法添加图例?
【解决方案2】:

我认为您必须添加参数position = "dodge"

 ggplot(tmpData, aes(x = x, y = y, fill = fill,)) +
  geom_dotplot(binaxis = "y", stackdir = "center", dotsize = 4, position = "dodge")

【讨论】:

  • 我确实尝试过,但这个解决方案消除了“x”和“y”周围的点的良好居中(就像 stackgroups=TRUE)。
  • @Kristoffer Vitting-Seerup 这与 stackgroups=TRUE 不完全相同,它们是对称绘制的,在垂直轴 x 和 y 的左侧和右侧组 A。所以组是对齐的,而在您的示例中它们不是。
  • 没错,但这不是我想做的。我希望它们像第一个情节一样居中,只是添加了颜色:-)
猜你喜欢
  • 2015-10-19
  • 2014-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 2020-04-09
  • 1970-01-01
相关资源
最近更新 更多