以计数作为标签的 2D 摘要图

alk*_*989 6 plot r ggplot2

value我在特定点 (lon和)测量了数量 ( ) lat,如下面的示例数据:

library(ggplot2)
set.seed(1)
dat <- data.frame(lon = runif(1000, 1, 15), 
                  lat = runif(1000, 40, 60), 
                  value = rnorm(1000))
Run Code Online (Sandbox Code Playgroud)

我想用空间颜色对测量值进行二维汇总(例如平均值),最重要的是我想将计数显示为标签。

我可以绘制标签和摘要图

## Left plot
ggplot(dat) +
  aes(x = lon, y = lat, z = value) +
  stat_summary_hex(bins = 5, fun = "mean", geom = "hex")
## Right plot
ggplot(dat) +
  aes(x = lon, y = lat, z = value) +
  stat_binhex(aes(label = ..count..), bins = 5, geom = "text")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但当我将两者结合起来时,我失去了总结:

ggplot(dat) +
  aes(x = lon, y = lat, z = value) +
  stat_summary_hex(bins = 5, fun = "mean", geom = "hex") +
  stat_binhex(aes(label = ..count..), bins = 5, geom = "text")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我可以实现相反的效果,将颜色和摘要视为标签:

ggplot(dat, aes(lon, lat, z = value)) +
  geom_hex(bins = 5) +
  stat_summary_hex(aes(label=..value..), bins = 5, 
                   fun = function(x) round(mean(x), 3), 
                   geom = "text")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

alk*_*989 6

在编写这个问题时,我花了几个小时进行测试,我找到了一个解决方案:在文本中添加一个fill=NULL, 或给我我想要的东西。fill=mean(value)下面是代码及其结果图;唯一的区别是图例的标签。

但感觉很老套,所以我希望有更好的解决方案。

ggplot(dat) +
  aes(x = lon, y = lat, z = value)  +
  stat_summary_hex(bins = 5, fun = "mean", geom = "hex") +
  stat_binhex(aes(label = ..count.., fill = NULL), bins = 5, geom = "text") +
  theme_bw()



ggplot(dat) +
  aes(x = lon, y = lat, z = value)  +
  stat_summary_hex(bins = 5, fun = "mean", geom = "hex") +
  stat_binhex(aes(label = ..count.., fill = mean(value)), bins = 5, geom = "text") +
  theme_bw()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 我认为使用“fill = NULL”是这里的“正确”答案。`StatBinhex` 有一个默认的美学映射 `fill = after_stat(count)` (然后将范围与 `stat_summary_hex()` 的范围合并以绘制指南,正如其他人所说)。通过指定“fill = NULL”,您将显式删除该映射。 (2认同)