Question

I am trying to replicate figure 6.11 from Hadley Wickham's ggplot2 book, which plots R colors in Luv space; the colors of points represent themselves, and no legend is necessary. enter image description here

Here are two attempts:

library(colorspace)
myColors <- data.frame("L"=runif(10000, 0,100),"a"=runif(10000, -100, 100),"b"=runif(10000, -100, 100))
myColors <- within(myColors, Luv <- hex(LUV(L, a, b)))
myColors <- na.omit(myColors)
g <- ggplot(myColors, aes(a, b, color=Luv), size=2)
g + geom_point() + ggtitle ("mycolors")

enter image description here

Second attempt:

other <- data.frame("L"=runif(10000),"a"=runif(10000),"b"=runif(10000))
other <- within(other, Luv <- hex(LUV(L, a, b)))
other <- na.omit(other)
g <- ggplot(other, aes(a, b, color=Luv), size=2)
g + geom_point() + ggtitle("other")

enter image description here

There are a couple of obvious problems:

  1. These graphs don't look anything like the figure. Any suggestions on the code needed?
  2. The first attempt generates a lot of NA fields in the Luv column (only ~3100 named colors out of 10,000 runs, versus ~9950 in the second run). If L is supposed to be between 0-100 and u and v between -100 and 100, why do I have so many NAs in the first run? I have tried rounding, it doesn't help.
  3. Why do I have a legend?

Many thanks.

Was it helpful?

Solution

You're getting strange colors because aes(color = Luv) says "assign a color to each unique string in column Luv". If you assign color outside of aes, as below, it means "use these explicit colors". I think something like this should be close to the figure you presented.

require(colorspace)
x <- sRGB(t(col2rgb(colors())))
storage.mode(x@coords) <- "numeric" # as(..., "LUV") doesn't like integers for some reason
y <- as(x, "LUV")
DF <- as.data.frame(y@coords)
DF$col <- colors()
ggplot(DF, aes( x = U, y = V)) + geom_point(colour = DF$col)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top