ggplot2可视化彼此重叠绘制的点数:stat_bin2d或geom_tile或点大小?

时间:2013-06-24 15:17:52

标签: r ggplot2

我的问题很简单:我有一些带有x,y坐标的点,它们位于由1x1正方形组成的矩形网格内。这些点具有平均坐标,因此几个点被赋予相同的坐标(它们完全重叠)。可重复的例子:

# generate fake data
y <- seq(from=0.5, to=9.5, by=1)
x <- seq(from=0.5, to=4.5, by=1)
xnew <- sample(x,100,replace=T)
ynew <- sample(y,100,replace=T)
data <- data.frame(xnew,ynew)

# create chart
ggplot(data, aes(x=xnew, y=ynew)) + geom_point()

我想表示特定位置的点的频率(x,y坐标,表示特定的方块)。 stat_bin2d是向正确方向迈出的一步,但是这些箱子莫名其妙地(对我而言)放置在地图上的不同位置,这使得难以直观地看到分布。

我可以想象两种不同的解决方案:

1)有没有办法将这些垃圾箱放在点上?有时左下角位于该点,有时是右下角等,如下所示:as in here

此外,如果框大到足以相互接触,那将是理想的,但是当我更改binwidth=c(1,1)中的stat_bin2d()时,它实际上会更改计数,尽管这些框不应重叠因为所有点都至少相距1平方。

或使用磅值:

2)我更喜欢大小会反映浓度的点(黑色和白色也会更好)。我尝试使用geom_point():

ggplot(data, aes(x=xnew, y=ynew))+geom_point(aes(x=xnew,y=ynew, size=..count..))

但我得到了

Error in eval(expr, envir, enclos) : object 'count' not found

然后,如果我添加`stat =“bin”,它与y的赋值冲突。我看了一眼:Why wont ggplot2 allow me to set a size for each individual point?,但无法使其发挥作用。

感谢您提供任何帮助。

2 个答案:

答案 0 :(得分:5)

ggplot2版本2.0.0引入geom_count()来做到这一点。使用您的数据:

ggplot(data, aes(x=xnew,y=ynew)) +
  geom_count()

收率: geom_count chart

答案 1 :(得分:4)

data2 <- aggregate(data$x,by=list(x=data$x,y=data$y),length)
names(data2)[3] <- "count"


ggplot(data2, aes(x=x,y=y)) + geom_point(aes(size=count))

enter image description here