I implemented the following function to plot the different colors used by ggplot. They function also plots the hex color values in the legend. However, somehow, the assignment of the colors and the hex values is wrong and I do not understand why. I sorted the hex colors before adding them to the data frame data
which is then used in the ggplot2 function. I thought that would fix the problem but it did not. I also created the vector col
which contains the hex as well as the rgb color values which I actually want to have as the legend but I am also struggling to get this working
ggplot_colors <- function(n, size=8, alpha=1) {
library(grDevices)
hues = seq(15, 375, length=n+1)
cols_hex <- sort(hcl(h=hues, l=65, c=100)[1:n])
cols_rgb <- col2rgb(cols_hex)
cols_rgb <- apply(cols_rgb, 2, function(x){paste(x, collapse=",")})
cols <- paste(cols_hex, cols_rgb, sep="; ")
data <- data.frame(x=1:length(cols),
y=1:length(cols),
cols_hex=cols_hex,
cols_rgb=cols_rgb,
cols=cols)
ggplot(NULL) +
geom_point(data=data,
aes(x=x, y=y, colour=cols_hex), size=size, alpha=alpha)
}
ggplot_colors(15, 8, 1)
The red color which as a RGB value of (248, 118, 109) and a hex value of F8766D is assigned the hex value of 00B0F6 in the legend