0

I want to draw a hexbin plot with ggplot, but with log scale "pretty" breaks for the frequency. Consider

df = data.frame(a=rnorm(1000)); df$b <- df$a+rnorm(1000);

I used this answer to get pretty breaks on linear scale

ggplot(df, aes(a,b)) +
  geom_hex(aes(fill=cut(..value..,breaks=pretty(..value.., n=10)))) +
  scale_fill_discrete("Frequency")

This works. Now say I want to use log scale pretty breaks. So I used the idea from another answer to define

base_breaks <- function(n = 10){
    function(x) {
        axisTicks(log10(range(x, na.rm = TRUE)), log = TRUE, n = n)
    }
}

and try to do

ggplot(df, aes(a,b)) + 
  geom_hex(aes(fill=cut(..value..,breaks=base_breaks(n=10)(..value..))))

but it is not able to find the function. It says:

Error in cut.default(value, breaks = base_breaks(n = 10)(value)) : 
  could not find function "base_breaks"

Even though base_breaks is defined.

> base_breaks(n=10)(c(1:1000))
[1]    1    5   10   50  100  500 1000

How can I make my function visible in whatever environment ggplot is calling it? I even defined it as a global variable with

base_breaks <<- function(n = 10){
    function(x) {
        axisTicks(log10(range(x, na.rm = TRUE)), log = TRUE, n = n)
    }
}

but I still get the same error.

Community
  • 1
  • 1
highBandWidth
  • 16,751
  • 20
  • 84
  • 131

1 Answers1

0

I am not sure about it, but you could try simplifying the function like this:

base_breaks <<- function(n = 10, x){
    axisTicks(log10(range(x, na.rm = TRUE)), log = TRUE, n = n)
}

Maybe the problem is that you have a function whose result is another function, and that could be causing the error. With this aproach you would have the values more directly. Check it out!

I can't check it myself, since I get an error object 'value' not found...

Tom Fuller
  • 5,291
  • 7
  • 33
  • 42
Javi_VM
  • 505
  • 2
  • 10