关于如何在geom_bin2d
上标记计数的一个很好的答案可以在这里找到:
Getting counts on bins in a heat map using R
然而,当修改它以具有对数X轴时:
library(ggplot2)
set.seed(1)
dat <- data.frame(x = rnorm(1000), y = rnorm(1000))
# plot MODIFIED HERE TO BECOME log10
p <- ggplot(dat, aes(x = x, y = y)) + geom_bin2d() + scale_x_log10()
# 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")
这会产生很难映射到各自点的标签。
如何更正基于geom_text
的标签以正确映射到各自的点?
答案 0 :(得分:2)
直接在x值上应用对数变换,而不是按比例。只更改代码的一行:
p <- ggplot(dat, aes(x = log10(x), y = y)) + geom_bin2d()
这允许保留负值并产生以下图: