当我aes(fill=...)用来指示a中的因子水平时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")
Run Code Online (Sandbox Code Playgroud)
不知何故,这种参数组合(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")
Run Code Online (Sandbox Code Playgroud)
稍微复杂一点的构造可能会产生与您想要的类似的结果:它使用 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)
Run Code Online (Sandbox Code Playgroud)