Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - Contrast between label and background: determine if color is light or dark

I have a barplot with labels in white. Sometimes the color of background is too light and the white label becomes illegible. I'm looking for a function that takes a color value and returns whether the color is dark or light. Then I can set the label color to white or black accordingly to obtain the best contrast against the background.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Here's a strategy to implement picking a text color of black vs white based on the intensity scale in the (second) link provided by @MrFlick.

The blog cited a W3C publication: a standard formula for calculating the perceived brightness of a color that used an algorithm for RGB encoded colors:

 ((Red value X 299) + (Green value X 587) + (Blue value X 114)) / 1000

The col2rgb function delivers a 3-row matrix which I multiply by the factors offered in that webpage. I used an example of "red" as a background color and the chosen text would then be "white"

 c( "black", "white")[  1+(sum( col2rgb("red") *c(299, 587,114))/1000 < 123) ]
[1] "white"

Implemented as a function:

isDark <- function(colr) { (sum( col2rgb(colr) * c(299, 587,114))/1000 < 123) }
isDark("red")
[1] TRUE

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...