使用 R 计算热图中的 bins

Getting counts on bins in a heat map using R

这个问题来自这两个主题:

How to use stat_bin2d() to compute counts labels in ggplot2?

How to show the numeric cell values in heat map cells in r

第一个话题,用户想用stat_bin2d生成热图,然后想把每个bin的计数写在热图上面。用户最初想要使用的方法不起作用,最佳答案说明 stat_bin2d 旨在与 geom = "rect" 一起使用,而不是 "text"。没有给出满意的答复。

第二个问题与第一个问题几乎相同,有一个关键的区别,第二个问题中的变量是文本,而不是数字。答案产生了预期的结果,将 bin 的计数值放在 stat_2d 热图中的 bin 上。

为了比较这两种方法,我准备了以下代码:

    library(ggplot2)
    data <- data.frame(x = rnorm(1000), y = rnorm(1000))
    ggplot(data, aes(x = x, y = y))
      geom_bin2d() + 
      stat_bin2d(geom="text", aes(label=..count..))

我们知道这首先会给您带来错误:

"Error: geom_text requires the following missing aesthetics: x, y".

与第一个问题相同的问题。有趣的是,从 stat_bin2d 更改为 stat_binhex 效果很好:

    library(ggplot2)
    data <- data.frame(x = rnorm(1000), y = rnorm(1000))
    ggplot(data, aes(x = x, y = y))
      geom_binhex() + 
      stat_binhex(geom="text", aes(label=..count..))

这很好,但总的来说,我认为十六进制合并不是很清楚,并且出于我的目的,它不适用于我试图描述的数据。我真的很想用 stat_2d.

为了让它起作用,我根据第二个答案准备了以下解决方法:

    library(ggplot2)
    data <- data.frame(x = rnorm(1000), y = rnorm(1000))
    x_t<-as.character(round(data$x,.1))
    y_t<-as.character(round(data$y,.1))
    x_x<-as.character(seq(-3,3),1)
    y_y<-as.character(seq(-3,3),1)
    data<-cbind(data,x_t,y_t)



    ggplot(data, aes(x = x_t, y = y_t)) +
      geom_bin2d() + 
      stat_bin2d(geom="text", aes(label=..count..))+
      scale_x_discrete(limits =x_x) +
      scale_y_discrete(limits=y_y) 

这解决了允许对数字数据进行分箱的问题,但要这样做,您必须在将其放入 ggplot 之前确定分箱宽度(我通过舍入完成)。我其实是在写这个问题的时候想出来的,所以我还是做完吧。 这是结果:(原来我不能 post 图片)

所以我真正的问题是,有没有人有更好的方法来做到这一点?我很高兴我至少让它工作了,但到目前为止我还没有看到在使用数值变量时将标签放在 stat_2d 垃圾箱上的答案。

有没有人有一种方法可以将 x 和 y 参数从 stat_2dbin 传递给 geom_text 而无需使用变通方法?任何人都可以解释为什么它适用于文本变量而不适用于数字吗?

另一种解决方法(但工作量可能较小)。与 ..count.. 方法类似,您可以分两步从绘图对象中提取计数。

library(ggplot2)

set.seed(1)
dat <- data.frame(x = rnorm(1000), y = rnorm(1000))

# plot
p <- ggplot(dat, aes(x = x, y = y)) + geom_bin2d() 

# Get data - this includes counts and x,y coordinates 
newdat <- ggplot_build(p)$data[[1]]

# add in text labels
p + geom_text(data=newdat, aes((xmin + xmax)/2, (ymin + ymax)/2, 
                  label=count), col="white")