Test a palette's contrast before it ships
Task
Calculate the WCAG contrast ratio of seven colours against a white background, and find which of them are dark enough to use for text and thin lines.
Steps
- Write
lab/colour/contrast.py. For each colour, convert each channel to c = value / 255, then to c / 12.92 if c is at most 0.03928, otherwise ((c + 0.055) / 1.055) ** 2.4. The relative luminance L is 0.2126 R + 0.7152 G + 0.0722 B. - The contrast ratio of two colours is (L1 + 0.05) / (L2 + 0.05), with L1 the lighter. White has L = 1.
- Calculate the ratio against white for #1f77b4, #ff7f0e, #2ca02c, #d62728, #767676, #999999 and #0b5394, and save
lab/colour/contrast.csvwith headercolour,ratio,passes, ratio to two decimal places, and passesyeswhen the ratio is at least 4.5 (the WCAG AA level for normal text), otherwiseno.
Verify
These checks run in a POSIX shell with Python 3: Terminal on macOS or Linux, and on Windows Git Bash (it comes with Git for Windows) or WSL. On Windows, python3 is often a Microsoft Store placeholder that prints “Python was not found”; run alias python3=py in Git Bash first.
awk -F, 'NR>1 {print $1": "$2" "$3}' lab/colour/contrast.csv
awk -F, 'NR>1 && $3=="yes"' lab/colour/contrast.csv | wc -l
Four pass: #1f77b4 at 4.82, #d62728 at 5.02, #767676 at 4.54 and #0b5394 at 7.84. Three fail: #ff7f0e at 2.53, #2ca02c at 3.40 and #999999 at 2.85. The orange and green of a common default palette are too light for text on white, and red with green is the pair colour-blind readers cannot separate -- so label the series as well as colouring them.
This is an independent study companion for CompTIA Data+ DA0-002 and is not produced by or endorsed by CompTIA.