Home > Net >  How to get hexbin center coordinates?
How to get hexbin center coordinates?

Time:04-30

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.

CodePudding user response:

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 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)

  • Related