Search code examples
rggplot2hexagonal-tiles

How to fix overlapping hexagons with geom_hex() and ggplot()?


I am plotting some data, basically I have coordinates and a value for each point. I wanted to make a hexagon map, with each hexagon averaging all the point values that correspond to that hexagon.

I manage to produce the map, but the some of the hexagons are overlapping and I am not sure how to fix it.

Here is my code:

pp = ggplot(df, aes(x = lon, y = lat, fill=value, group=value)) +
  geom_hex(bins = 50, linewidth = 10) 
pp

And the plot:

enter image description here


Solution

  • If you want the hexagons to be colored according to the average value, you will need stat_summary_hex, passing the numeric value to the z aesthetic, which by default is averaged in each hex bin.

    Don't group by value - this effectively creates a layer of hexbins for each value, and this is what leads to the bins being in different positions in each group. Also, the values can't be averaged if they are in different groups.

    library(ggplot2)
    
    ggplot(df, aes(x = lon, y = lat)) +
      stat_summary_hex(aes(z = as.numeric(as.character(value))),
                       bins = 50, linewidth = 10) +
      scale_fill_gradientn(colors = scales::hue_pal()(5))
    

    Note that the latest CRAN version of ggplot has an issue with hex-binning, and you will need to install the development version to get a decent result here. See this question for further details.

    Created on 2023-01-04 with reprex v2.0.2


    Data used

    set.seed(1)
    
    df <- data.frame(lon = rnorm(1000, 5.5), lat = rnorm(1000, 52.5),
                     value = factor(sample(0:4, 1000, TRUE)))