使用`scale_x_log10`时,如何将`geom_text`准确地映射到`geom_bin2d`?

时间:2015-07-01 13:10:52

标签: r ggplot2

关于如何在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的标签以正确映射到各自的点?

1 个答案:

答案 0 :(得分:2)

直接在x值上应用对数变换,而不是按比例。只更改代码的一行:

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

这允许保留负值并产生以下图: enter image description here