Search code examples
rggplot2geom

Fixing Fill in geom_hex


I'm struggling to get geom_hex to fill with a certain variable. My goal is to get geom_hex to fill with the variable xRV, with lower values being red and higher values being blue, but as things stand all I get is gray hexagons.

Here's the df:

IVB <- c(10, 15, 20, 17, 17.5, 20, 17, 16.5, 21.3, 12.5, 10.9)
RelZ <- c(66, 75, 70, 67, 68.3, 67.6, 70.3, 72, 65.3, 55.6, 71)
xRV <- c(-.01, .13, -.15, .5, -.03, -.06, .07, .1, -.02, .05, .01)
miheat <- data.frame(IVB, RelZ, xRV)

Here's the code I've been running that hasn't been working:

library(ggplot2)
library(hexbin)
ggplot(miheat, aes(x = RelZ, y = IVB)) + geom_hex(aes(fill = xRV)) + scale_fill_gradient2(low = "red" , mid = "white" , high = "blue", space = "Lab")

Here's what the output looks like when I run the code above on all of the df


Solution

  • You were close in what you were doing in your question. Instead of using fill what you should be doing is using weight

    library(ggplot2)
    library(hexbin)
    ggplot(miheat,aes(x = RelZ, y = IVB, weight = xRV)) + geom_hex() + scale_fill_gradient2(low = "red" , mid = "white" , high = "blue", space = "Lab", midpoint = 0)
    

    example