Search code examples
rggplot2plottidyversebinning

Uneven binning and its plotting in R using ggplot2


Is there any way to use a vector of numbers within the binwidth for geom_bin_2d? I would like to create a binned heatmap with irregular/uneven bin lengths, but I am not sure how to do it.

A reproducible example

library(tidyverse)

data <- tibble(x = sample(100),
               y = sample(100)) %>%
  mutate(x = x * 1.2,
         y = y * 0.8)

binX <- c(18, 39, 60, 81, 102, 120)
binY <- c(18, 30, 50, 62, 80)

data %>%
ggplot() +
geom_bin_2d(aes(x = x, y = y), binwidth = c(binX, binY))

Solution

  • You can pass the x and y bins in a list to the breaks argument:

    ggplot(data) + geom_bin_2d(aes(x, y), breaks = list(binX, binY))
    

    enter image description here