繁体   English   中英

如何将 ggplot2 的 geom_dotplot() 与填充和组一起使用

[英]How to use ggplot2's geom_dotplot() with both fill and group

我真的很喜欢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)

导致这个 plot:

没有颜色的点图

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

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

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

带颜色的点图

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

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)

带有堆栈组的 dotpoot

但后来我失去了数据的中心到其他 3 个图中找到的“x”和“y”。

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

如果您愿意接受一些 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)

在此处输入图像描述

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

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

在此处输入图像描述

library(ggplot2)

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

# After adding fill
ggplot(tmpData, aes(x=x, y=y, fill=fill)) +   
geom_dotplot(binaxis='y', stackdir = "center", binpositions="all", stackgroups=TRUE,dotsize=4)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM