I'm trying to make an image similar to this one by OpenWetWare (source). I generate the curves using the colourvision package. I made the color spectrum with the rainbow() palette, based on code by @baptiste found here (and repeated here).

Problem and question
The gradient I produced does not correspond to the actual color frequencies. How can I generate a spectrum that coincides (at least closely) with the actual color frequencies (e.g., 550 nm in green-yellow territory, not cyan). I'm certain rainbow() is probably not the way to generate the needed palette but I do not know what would be the best way.
MWE
library(colourvision)
library(ggplot2)
library(grid)
gradient <- t(rev(rainbow(20))) # higher value for smoother gradient
g <- rasterGrob(gradient, width = unit(1, "npc"), height = unit(1, "npc"), interpolate = TRUE)
human <- photor(lambda.max = c(420, 530, 560), lambda = seq(400, 700, 1))
ggplot(data = human, aes(x = Wavelength)) +
annotation_custom(g, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf) +
geom_line(aes(y = lambda.max420), color = "white") +
geom_line(aes(y = lambda.max530), color = "white") +
geom_line(aes(y = lambda.max560), color = "white") +
scale_x_continuous(breaks = seq(400, 700, 50)) +
labs(x = NULL, y = NULL) # Save space for question
Result

You could use w_length2rgb from the photobiology package:
library(photobiology)
gradient <- t(w_length2rgb(400:700))
#then the rest of your code as it is

Following your comment, and just for completeness, you could also use the data from cvrl.org, which I think looks better...
conesdata <- read.csv("http://www.cvrl.org/database/data/cones/linss10e_5.csv")
names(conesdata) <- c("Wavelength", "Red", "Green", "Blue")
conesdata[is.na(conesdata)] <- 0
conesdata$colour <- rgb(conesdata$Red, conesdata$Green, conesdata$Blue)
gradient <- t(conesdata$colour[conesdata$Wavelength >= 400 & conesdata$Wavelength <= 700])
#then the rest of your code as before

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