Search code examples
r

Assign stat_summary_hex color depending on data frame column RGB color value R


As see below, I created new column with RGB gradient color for each points in the data frame.

I try to assign this RGB color value to the corresponding point, converted to hexagon, using stat_summary_hex function.

I try to use scale_fill_manual function as suggest by https://stackoverflow.com/a/35280407/15834162 but unsuccessfully.

Any suggestions? Thanks in advance!

See below a reproductible example, inspired by https://stackoverflow.com/a/75010172/15834162

# generate data frame
df <- data.frame(lon = rnorm(1000, 5.5), lat = rnorm(1000, 52.5),
                 value = 1:nrow(df) )

# plot
require(ggplot2)
ggplot(df, aes(x = lon, y = lat)) +
  stat_summary_hex(aes(z = as.numeric(as.character(value))),
                   bins = 50, linewidth = 10) +
  scale_fill_gradientn(colors = scales::hue_pal()(5))

# define x y axis
x = df$lon
y = df$lat

# calculate rgb gradient (see https://doi.org/10.1111/ddi.12566)
rgb <- matrix(NA, ncol = 3, nrow = length(x))
rgb[, 1] <- (x - min(x)) / (max(x) - min(x)) * 255
rgb[, 2] <- (y - min(y)) / (max(y) - min(y)) * 255
rgb[, 3] <- c(255 - rgb[, 1])

# Define color
require(grDevices)
df$rgb <- rgb(rgb[, 1], rgb[, 2], rgb[, 3], maxColorValue = 255)

# plot
ggplot(df, aes(x = lon, y = lat)) +
  stat_summary_hex(aes(z = as.numeric(as.character(value))),
                   bins = 50, linewidth = 10) +
  scale_fill_manual(values = df$rgb) # error

Solution

  • Not too sure what you are after. Simplified

    Calculation

    d$rgb = with(d, {
      x = lon; y = lat
      r = (x - min(x)) / (max(x) - min(x))
      g = (y - min(y)) / (max(y) - min(y)) 
      grDevices::rgb(r, g, 1-r)
    })
    

    and plot

    library(ggplot2)
    ggplot(d, aes(x = lon, y = lat, fill = rgb)) +
    stat_summary_hex(aes(z = value), bins = 50, linewidth = 10) +
      scale_fill_identity()
    

    Data

    d generated by

    set.seed(20250220)
    n = 1e4; d = data.frame(lon = rnorm(n, 5.5), lat = rnorm(n, 52.5), value = seq(n))