Convert visible wavelengths to Hex values in R.
# Install from GitHub:
install.packages("devtools")
devtools::install_github("roaldarbol/wavecolour")
wavecolour
supplies 3 low-level functions for converting wavelengths into colour codes:
wavelength_to_hex()
wavelength_to_rgb()
rgb_to_hex()
Additionally, it supplies a colour palette which can be used with ggplot2
as:
scale_colour_wavelength()
/scale_color_wavelength()
scale_fill_wavelength()
The scales are opinionated, and will return black for anything outside the visible spectrum (380 to 750). If you just need a palette with these colours, the rainbow
palette is the way to go - however, I would highly advise you to choose a better alternative, e.g. viridis
.
# Create single colour
col <- wavelength_to_hex(560)
# Create palette
wavelengths <- seq(from = 380, to = 750, by = 1)
hex_pal <- sapply(wavelengths, wavelength_to_hex)
rgb_pal <- sapply(wavelengths, wavelength_to_rgb)
library(ggplot2)
library(dplyr)
library(wavecolour)
# Create data
wavl <- seq(from = 300, to = 790, length.out = 500)
wavl_sin <- sin((wavl * pi) / (180)) + 1.5
wavl <- bind_cols(wavl, wavl_sin)
names(wavl) <- c("wavelength", "intensity")
# Create plot
ggplot(wavl, aes(wavelength, intensity)) +
geom_segment(aes(xend=wavelength, yend=0, colour = wavelength), size = 1) +
geom_line() +
scale_colour_wavelength() +
theme_minimal()
Adapted from Noah's Python implementation, who adapted from Dan Bruton's Fortran implementation.