繁体   English   中英

在R中的ggplot2 geom_dotplot中使用填充美学时的重叠点

[英]Overlapping points when using fill aesthetic in ggplot2 geom_dotplot in R

当我使用aes(fill=...)指示geom_dotplot的因子水平时,不同因子水平的点彼此重叠。 尤其是对于大型数据集,这变得很麻烦。

下面,我提供了一个最小的示例和图形,在该示例中,我首先绘制了没有着色因子水平的数据集,然后添加了fill以指示因子水平,这导致了点彼此重叠。 如何避免这种情况?

我在这里知道类似的问题。 但是,给出的答案不能解决此问题。

library("ggplot2")

n <- 200
x <- data.frame(x = sample(x = letters[1:3], size = n, replace = TRUE),
                y = rnorm(n = n, mean = 0, sd = 1),
                a = sample(x = letters[4:5], size = n, replace = TRUE))

p1 <- ggplot(x, aes(x = x, y = y))
p1 <- p1 + geom_dotplot(binaxis = "y", stackdir = "center")
p2 <- ggplot(x, aes(x = x, y = y, fill = a))
p2 <- p2 + geom_dotplot(binaxis = "y", stackdir = "center")

minimal_example_dotplot

不知何故,使用stackgroups = T结合使用binpositions =“ all”的这种参数组合给出了一个不错的结果,但仅以x变量的中心级别为中心。

ggplot(x, aes(x = x, y = y, fill=a)) + 
  geom_dotplot(binaxis = "y", 
               stackdir = "centerwhole", 
               method="dotdensity",
               stackgroups = T,
               binpositions="all")

在此处输入图片说明

稍微复杂一点的构造可能会产生与您想要的结果类似的结果:它使用grid.arrange和一个特殊函数来共享一个公共图例(请参阅此处以获取grid_arrange_shared_legend函数的代码)

for (i in 1:3){
  assign(paste0("g", i), ggplot(x %>% filter(x==levels(x$x)[i]), aes(x = x, y = y, fill=a)) + coord_cartesian(ylim=c(-3.5, 3.5))+
  geom_dotplot(binaxis = "y", stackdir = "center", method="dotdensity", stackgroups = T, binpositions="all"))
}
grid_arrange_shared_legend(g1, g2, g3)

在此处输入图片说明

暂无
暂无

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

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