Search code examples
rcolorsrgbggtern

Use RGB color triangle with ggtern() to spot a color


I have a RGB color triangle thanks to Edward answers here with tiny modifications:

plot(NA,NA,xlim=c(0,1),ylim=c(0,1),asp=1,bty="n",axes=F,xlab="",ylab="")
segments(0,0,0.5,sqrt(3)/2)
segments(0.5,sqrt(3)/2,1,0)
segments(1,0,0,0)
# sm - how smooth the plot is. Higher values will plot very slowly
sm <- 500
for (y in 1:(sm*sqrt(3)/2)/sm){
  for (x in (y*sm/sqrt(3)):(sm-y*sm/sqrt(3))/sm){
## distance from base line:
d.red = y
## distance from line y = sqrt(3) * x:
d.green = abs(sqrt(3) * x - y) / sqrt(3 + 1)
## distance from line y = - sqrt(3) * x + sqrt(3):
d.blue = abs(- sqrt(3) * x - y + sqrt(3)) / sqrt(3 + 1)
points(x, y, col=rgb(d.red, d.green, d.blue), pch=19)
  }
}

I also have one RGB code color (for example (232, 103, 101)), and I would a big black point into this RGB color triangle on these coordinates.

That's why I would like to use ggtern()

# install.packages("ggtern")
library(ggtern)
df = data.frame(x=232, y=103, z=101)
breaks = seq(0,1,by=0.2)
#breaks = c(0,255)
ggtern(data = df, aes(x, y, z)) + 
geom_point(color = black) +  
# I use 255 as the triangle limit, because the RGB code is an [0, 255] interval.
limit_tern(breaks=breaks,labels=255*breaks) +
scale_color_gradient(rgb(d.red, d.green, d.blue))

So, my black point is not situated on the good coordinates, and my RGB triangle color isn't on the backbround of the ggtern. I'm not yet confortable with ggtern.. May I should make a data transformation before ?

Thanks for any help


Solution

  • I've found an over way with triangle.plot from ade4 package:

    My RGB data are in an object (RGB0) like this:

    head(RGB0)
          R  G  B
    [1,] 87 92 69
    [2,] 87 92 69
    [3,] 88 93 70
    [4,] 88 93 70
    [5,] 89 94 71
    [6,] 89 94 71
    ...
    

    And the code:

    library(ade4)
    
    data2= as.data.frame(RGB0) 
    head(RGB0)  
    
    data2$R <- RGB0[,1]/255     
    data2$G <- RGB0[,2]/255
    data2$B <- RGB0[,3]/255
    head(data2)
    
    
    triangle.plot <- triangle.plot(data2, clab = 0, cpoi = 2, addmean = F, show = FALSE, addaxes = F, scale = F)
    points(triangle.plot, pch = 19, cex = 1, col = nacreHEX)  
    

    And here there the result: triangle.plot result