gplot2 grids overlap out of boundary

Viewed 129

I create points uniformly in [0,1] and each point has observations. But ggpolot shows some observations larger than 1 which is outside of the boundary. How come this can happen even though coordinates are within 0 and 1 range? Do you have any idea how to avoid this?

x=runif(10^6)
y=runif(10^6)
z=rnorm(10^6)

new.data=data.frame(x,y,z)

library(ggplot2)

ggplot(data=new.data) + stat_summary_2d(fun = mean, aes(x=x, y=y, z=z))

enter image description here

2 Answers

It’s an issue related to the grid used for binning. Let’s use a smaller example.

set.seed(42)
x=runif(10^3)
y=runif(10^3)
z=rnorm(10^3)

new.data=data.frame(x,y,z)

library(ggplot2)

(g <- ggplot(data=new.data) + 
    stat_summary_2d(fun = mean, aes(x=x, y=y, z=z))  +
    geom_point(aes(x, y)))

Now let’s zoom at that box on the upper left corner

g + coord_cartesian(xlim = c(0.02, 0.075), ylim = c(0.99, 1.035), 
                    expand = FALSE)

As you can see, that box starts below y = 1 but extends above that value because you are binning observations according to some binwidth. The same phenomenon can occur if you use a histogram.

ggplot(data.frame(x = runif(1000, 0, 1)), aes(x)) +
  geom_histogram()
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

In geom_histogram this can be aboided by setting the boundary argument to 0 and the amount of bins to a multiple of the total length.

ggplot(data.frame(x = runif(1000, 0, 1)), aes(x)) +
  geom_histogram(boundary = 0, binwidth = 0.1)

So the solution in your case is to set binwidth to 1/n where n is an integer

ggplot(data=new.data) + 
    stat_summary_2d(fun = mean, aes(x=x, y=y, z=z), binwidth = 0.1)  +
    geom_point(aes(x, y))

Created on 2018-11-04 by the reprex package (v0.2.1.9000)

You have:

set.seed(1)
x=runif(10^6)

Here's what's going on behind the scenes:

bins <- 30L
range <- range(x)
origin <- 0L
binwidth <- diff(range)/bins
breaks <- seq(origin, range[2] + binwidth, binwidth)
bins <- cut(x, breaks, include.lowest = TRUE, right = TRUE, dig.lab = 7)
table(bins)
# ...
# (0.8999984,0.9333317]   (0.9333317,0.9666649]   (0.9666649,0.9999982] 
# 33217                   33039                   33297 
# (0.9999982,1.033331] 
# 1 
max(x)
# [1] 0.9999984

How come this can happen even though coordinates are within 0 and 1 range

  1. binning starts at 0 (not a the minimum value)
  2. each bin has a size of binwidth
  3. there's a final bin that ends at the maximum value + binwidth, which gets the maximum value

Do you have any idea how to avoid this?

One way would be to define your own breaks:

ggplot(data=new.data) + stat_summary_2d(fun = mean, aes(x=x, y=y, z=z), breaks = seq(0, 1, .1))
Related