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)
在编写这个问题时,我花了几个小时进行测试,我找到了一个解决方案:在文本中添加一个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)