Search code examples
rhexagonal-tiles

How to convert x y coordinates to hexbin center coordinates


I'm aware of the hexbin package, but I don't want to summarize the data at this point. I don't draw my plots in R, so I have no need for hexbin objects or many other things in this package.

I simply want to convert/round each point's coordinates to the xy coordinates of the center of the hexagon that contains the point. In other words, instead of the hexbin function returning a hexbin object, I want to return x and y coordinates of hexagon centers that correspond to the input coordinates.

I assumed I would find something useful in the source code of the hexbin function, but I'm kinda lost there. I don't want to write my own function if it's already been done, so any advice is welcome.


Solution

  • Assign your hexbin with desired bin sizes to an object and then check the structure. The center of mass is given by @xcm and @ycm. See ?hexbin.

    An example is shown below.

    library(hexbin)
    mtcars_hexbin <- hexbin(mtcars$mpg ~ mtcars$hp, xbins = 5, IDs= TRUE)
    str(mtcars_hexbin)
    
    # The x, y of center of mass are given by:
    mtcars_hexbin@xcm
    mtcars_hexbin@ycm
    

    Edited to answer comment: If IDs=TRUE, then the output @cID gives the cell number to which each original non-aggregated points belong to. @cell gives you the cell number associated with @xcm, @ycm center of mass coordinates. @count tells you how many points belong to a cell.

    mtcars_hexbin@cID
    mtcars_hexbin@cell
    mtcars_hexbin@count