8000 Use luminance to choose text colour over colour cycles · matplotlib/cheatsheets@201b89f · GitHub
[go: up one dir, main page]

Skip to content

Commit 201b89f

Browse files
committed
Use luminance to choose text colour over colour cycles
This uses the same algorithm as the [Specifying colors tutorial](https://matplotlib.org/stable/users/explain/colors/colors.html#comparison-between-x11-css4-and-xkcd-colors).
1 parent 436256c commit 201b89f

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

scripts/colors.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,19 @@
3333
for name, colors in palettes.items():
3434
C = mpl.colors.to_rgba_array(colors).reshape((1, len(colors), 4))
3535
ax.imshow(C, extent=[xmin, xmax, ymin, ymax])
36+
37+
# Drop alpha by assuming we're on a white background PDF.
38+
alpha = C[0, :, 3]
39+
rgb = C[0, :, :3] * alpha[:, np.newaxis] + (1 - alpha[:, np.newaxis])
40+
# Same calculation for luminance as
41+
# https://matplotlib.org/stable/users/explain/colors/colors.html#comparison-between-x11-css4-and-xkcd-colors
42+
luma = 0.299 * rgb[:, 0] + 0.587 * rgb[:, 1] + 0.114 * rgb[:, 2]
43+
3644
dx = (xmax-xmin)/len(colors)
3745
for i in range(len(colors)):
38-
color = "white"
39-
if colors[i] in ['1.0', 'w']: color = "black"
46+
text_color = "black" if luma[i] > 0.5 else "white"
4047
text = str(colors[i]).replace(' ', '')
41-
ax.text((i+0.5)*dx, (ymin+ymax)/2, text, color=color, zorder=10,
48+
ax.text((i+0.5)*dx, (ymin+ymax)/2, text, color=text_color, zorder=10,
4249
family="Source Code Pro", size=9, ha="center", va="cent 4162 er")
4350

4451
fig.savefig(ROOT_DIR / f"figures/colors-{name}.pdf")

0 commit comments

Comments
 (0)
0