【问题标题】:ggplot2 visualizing counts of points plotted on top of each other: stat_bin2d or geom_tile or point size?ggplot2 可视化绘制在彼此之上的点数:stat_bin2d 或 geom_tile 或点大小?
【发布时间】:2026-01-22 01:35:01
【问题描述】:

我的问题很简单:我有一些带有 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) 有没有办法将箱子放在点的中心?有时左下角是点,有时是右下角等像这样:

此外,如果盒子足够大以相互接触,那将是理想的,但是当我在 stat_bin2d() 中更改 binwidth=c(1,1) 时,它实际上会更改计数,尽管这些 bin 不应该重叠,因为所有点彼此相距至少 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?,但无法使其工作。

感谢您的帮助。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

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

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

    产量:

    【讨论】:

      【解决方案2】:
      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))
      

      【讨论】:

      • 太好了,@Roland,谢谢!这样就解决了积分问题。如果有人有想法,我仍然想知道另一种方式。
      最近更新 更多