4

A great answer on how to label the count on geom_bin2d, can be found here:

Getting counts on bins in a heat map using R

However, when modifying this to have a logarithmic X axis:

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")

This produces labels that are very poorly mapped to their respective points.

How can I correct the geom_text based labels to correctly map to thier respective points?

Community
  • 1
  • 1
DaveRGP
  • 1,430
  • 15
  • 34

1 Answers1

3

Apply logarithmic transformation directly on x values, not on scale. Change only one line of your code:

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

That allows to keep negative values and produces the following plot: enter image description here

inscaven
  • 2,514
  • 19
  • 29