在R中使用ggplot2 geom_dotplot中的填充美学时重叠点 [英] Overlapping points when using fill aesthetic in ggplot2 geom_dotplot in R

查看:2228
本文介绍了在R中使用ggplot2 geom_dotplot中的填充美学时重叠点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 aes(fill = ...)来指示 geom_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和一个特殊的函数来共享一个常见的图例(参见


When I use aes(fill=...) to indicate factor levels in a geom_dotplot, points of different factor levels overlap each other. Especially with large datasets, this becomes troublesome.

Below I have included a minimal example and figure, in which I first plot a dataset without colouring factor levels, and then I add fill to indicate factor levels, which leads to points overlapping each other. How can I avoid this?

I am aware of a similar question here; however, the answers given do not resolve this issue.

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

解决方案

Somehow this combination of arguments, with stackgroups=T combined with binpositions="all" gives a nice result but only centered for the central level of x variable.

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

A little bit more complicated construction could yield a result similar to what you want: it uses grid.arrange and a special function to share a common legend (see here for the code of the grid_arrange_shared_legend function)

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)

这篇关于在R中使用ggplot2 geom_dotplot中的填充美学时重叠点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆