Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

r - ggplot wrong color assignment

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)

enter image description here

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As you want to supply color names to argument colour= and display also a legend for this argument, you should add scale_colour_identity() to your last line in function. This scale ensures that values supplied will be interpreted as actual color values. Adding of argument breaks=cols_hex in function scale() will ensure ordering of names in legend.

ggplot(NULL) +     
geom_point(data=data, aes(x=x, y=y, colour=cols_hex), size=size, alpha=alpha) + 
        scale_colour_identity(guide="legend",breaks=cols_hex)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...