I'm trying to create a normal hexbin plot but instead of coloring the plot by count, the default, I would like to have it colored by the average value of a third variable. In my particular case, I cannot use the stat_summary_hex function.
library(ggplot2)
library(hexbin)
x <- rnorm(1e4, 0, 5)
y <- rnorm(1e4, 0, 10)
z <- rnorm(1e4, 20, 1)
data.frame(x, y, z) %>%
ggplot(mapping = aes(x = x, y = y, z = z)) +
geom_hex(bins = 20)
You can use the following code:
library(ggplot2)
library(hexbin)
library(ggraph)
x <- rnorm(1e4, 0, 5)
y <- rnorm(1e4, 0, 10)
z <- rnorm(1e4, 20, 1)
data.frame(x, y, z) %>%
ggplot(aes(x, y, z=z)) +
stat_summary_hex(fun = function(x) mean(x), bins = 20) +
scale_fill_viridis_c(option = "magma")
ggplotly()
Output:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With