Invert col2rgb and rgb2hsv

Im converts colors to HSV to reassign color. In fact, I am generating a gray gradient with gray.colors :

 (mydata <- 1 : 10) # For exposition only cols <- gray.colors(max(mydata)) 

However, what I really want is a gradient of white and red, not white and black. Fiddling around with the color picker convinced me that for this it should be enough to change the value and saturation to the colors of shades of gray, and then set the value to 1 (hue 0 already matches red).

Voting is easier:

 hsvc <-rgb2hsv(col2rgb(cols)) hsvc['s', ] <- hsvc['v', ] hsvc['v', ] <- 1 

However, to build these values, I now need to convert them back to color values โ€‹โ€‹of R. It seems that I can not do this due to the lack of hsv2col . Of course, theres hsv that claims to be this, but you cannot name it with the hsvc value above - even with one column:

 hsv(hsvc[, 1]) # plots *three* (wrong) colour values instead of one 

And R cannot directly use HSV values:

 plot(1, 1, pch = 20, col = cols[1]) # Works, grey dot plot(1, 1, pch = 20, col = hsvc[, 1]) # Nothing plotted 

How to get the returned R color values โ€‹โ€‹back from the HSV value matrix?

+4
source share
2 answers

Use do.call and as.list to pass data to the corresponding hsv arguments:

 do.call(hsv,as.list(hsvc[,1])) [1] "#FFB3B3" plot(1,1, pch=20, col=do.call(hsv,as.list(hsvc[,1]))) # light red dot 

To do this for all your data:

 plot(mydata,col=apply(hsvc,2,function(x) do.call(hsv,as.list(x)))) # a symphony of red 

But it seems that the reassignment did not work correctly, since changes in intensity do not work in the same direction.

+2
source

Do you want to:

 > do.call(hsv, as.list(hsvc[, 1])) [1] "#FFB2B2" 

But then you really need to generalize this to work with all hsvc columns, so what about:

 sapply(data.frame(hsvc), function(x) do.call(hsv, as.list(x))) 

which gives

 > sapply(data.frame(hsvc), function(x) do.call(hsv, as.list(x))) X1 X2 X3 X4 X5 X6 X7 X8 "#FFB2B2" "#FF9393" "#FF7C7C" "#FF6969" "#FF5858" "#FF4A4A" "#FF3C3C" "#FF3030" X9 X10 "#FF2424" "#FF1919" 

or more beautiful

 > apply(hsvc, 2, function(x) do.call(hsv, as.list(x))) [1] "#FFB2B2" "#FF9393" "#FF7C7C" "#FF6969" "#FF5858" "#FF4A4A" "#FF3C3C" [8] "#FF3030" "#FF2424" "#FF1919 
+2
source

Source: https://habr.com/ru/post/1493014/


All Articles