0

I'm using R 3.6.0 with {ggplot2} 3.4.0.

Here is some code to demonstrate my issue:

library(ggplot2)
library(cowplot)
library(hexbin)

df <- data.frame(x = rnorm(1000), y = rnorm(1000))

plot_grid(
  ggplot(df) + geom_bin_2d(aes(x = x, y = y)),
  ggplot(df) + geom_hex(aes(x = x, y = y)),
  labels = c("bin", "hex"),
  label_size = 12
)

For me the legends of these two plots are nearly identical: a range of values from 0 to about 12.5 mapped to colours from dark blue to light blue.

The geom_bin_2d() plot shows, as expected, light blues in the middle and darker blues on the outside. However - for me - the geom_hex() plot does not have any colours at the light-blue end of the scale. The plot is almost uniformly dark blue, with a small amount of variation.

Two plots showing output using geom_bin_2d() and geom_hex()

Is it just me?!

I used the hexbin() function to confirm manually that the counts were in the expected range - which they were. So why aren't they being mapped to the fill aesthetic properly?

> summary(hexbin(df$x, df$y))
'hexbin' object from call: hexbin(x = df$x, y = df$y) 
n = 1000  points in nc = 351  hexagon cells in grid dimensions  36 by 31 
      cell            count             xcm                ycm          
 Min.   :  18.0   Min.   : 1.000   Min.   :-3.54600   Min.   :-3.06479  
 1st Qu.: 389.5   1st Qu.: 1.000   1st Qu.:-0.91158   1st Qu.:-0.92188  
 Median : 565.0   Median : 2.000   Median : 0.02048   Median : 0.07285  
 Mean   : 559.9   Mean   : 2.849   Mean   : 0.04781   Mean   : 0.03474  
 3rd Qu.: 726.5   3rd Qu.: 4.000   3rd Qu.: 0.98753   3rd Qu.: 0.98776  
 Max.   :1098.0   Max.   :12.000   Max.   : 4.50242   Max.   : 3.02475 
Michael Henry
  • 599
  • 2
  • 4
  • 17
  • Does this help? It sounds like there is a bug in geom_hex color mapping that might be fixed in the development version of ggplot2: https://stackoverflow.com/a/75004245/6851825 – Jon Spring Jan 05 '23 at 06:41
  • That is ridiculous that you replied within two minutes and it solved the problem! Thanks! – Michael Henry Jan 05 '23 at 06:54

1 Answers1

2

This is a bug in {ggplot2} - fixed in the development version. See:

Inaccurate mapping of gradient fill colours with bin counts in geom_hexbin in ggplot2

Michael Henry
  • 599
  • 2
  • 4
  • 17