How to get hexbin center coordinates?

Viewed 70
library(hexbin)
x <- rnorm(mean=1.5, 5000)
y <- rnorm(mean=1.6, 5000)
bin<-hexbin(x, y)
plot(bin@xcm, bin@ycm, pch=20)

I want to get the center coordinate of each hex in a hexbin plot. But xcm and ycm are not the centers of the hexagons as shown in the above example.

enter image description here

How to get the center coordinate of the hexagon? Two solutions are needed one for hexbin package, one for ggplot2.

2 Answers

You can use hcell2xy to extract the center co-ordinates of the hex bins. It returns a list with x and y components, so can be plotted directly:

library(hexbin)

set.seed(1)

x   <- rnorm(mean = 1.5, 5000)
y   <- rnorm(mean = 1.6, 5000)

bin <- hexbin(x, y, xbins = 30)

plot(bin)

plot(hcell2xy(bin))

enter image description here

In fact, the hcell2xy is what ggplot uses internally to get its points (inside the unexported function ggplot2:::hexBinSummarise

Created on 2022-04-30 by the reprex package (v2.0.1)

For ggplot2 try this:

library(tidyverse)

hex_plot <- tibble(
  x = rnorm(mean = 1.5, 5000),
  y = rnorm(mean = 1.6, 5000)
) |>
  ggplot(aes(x, y)) +
  geom_hex(binwidth = 1)

hex_coords <- ggplot_build(hex_plot)$data[[1]] |> 
  tibble() |> 
  select(x, y)

hex_plot + 
  geom_point(colour = "white", data = hex_coords)

Created on 2022-04-30 by the reprex package (v2.0.1)

Related