# Determining optimal hexagon size for hexbins?

I've grown rather fond of hexbins. However, I'm always stumped when it comes to setting the hexagon size. I mostly go by feel right now. I just tweak the size until it "looks good".

Is there a more scientific way of determining the hexagon sizes?

## 3 Answers

For a side project we used turf.js and set the hex based on the map extent.

``````    var dataConfig = self.dataConfig;
self.bounds = self.map.getBounds();
var hexW = (dataConfig.hexWidth / (self.origBounds._northEast.lng - self.origBounds._southWest.lng)) * (self.bounds._northEast.lng - self.bounds._southWest.lng);
var hexExtent = [self.bounds._southWest.lng,self.bounds._southWest.lat, self.bounds._northEast.lng, self.bounds._northEast.lat];
self.hexgrid = turf.hexGrid(hexExtent, hexW, dataConfig.hexUnit);
``````

Each usage of the hexgrid is going to be different depending on what you are displaying, so we still had to base it on some number that could be changed from the config. But the cool part is that the hex width is calculated as a proportion of the map extent. As you zoom in and out, the hex is recalculated to be the same proportion as the width was to the original map extent.

Using a PostGIS function, we've created hexagon layers at each basemap tile zoom level, starting at half a square km for level 13. That gives us enough layers to choose from to display things optimally (with a small amount of trial and error).

The function is here if its of interest, it allows you to specify your hexes by sq km:

https://github.com/minus34/postgis-scripts/tree/master/hex-grid

It depends. In reality you want sizes that reflect the scale the map will be shown at and if its interactive you want multiple sizes. The size should be large enough to have data in most of the shapes, but small enough to allow you to start to see any relevant patterns. I find you can create 3-5 scale layers and just use those repeatedly with different attributes appended. Don't try and game the shape to fit your area, you are biasing the visual results. Think of it as more a randomized areal sample mesh over your data.