Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 72e4f86

Browse files
Added support for shorthand hex colors.
1 parent bedb4d9 commit 72e4f86

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

lib/matplotlib/colors.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -215,20 +215,34 @@ def _to_rgba_no_colorcycle(c, alpha=None):
215215
"%(since)s and will be removed %(removal)s; please "
216216
"use lowercase instead.")
217217
if isinstance(c, str):
218-
# hex color with no alpha.
218+
# hex color in #rrggbb format.
219219
match = re.match(r"\A#[a-fA-F0-9]{6}\Z", c)
220220
if match:
221221
return (tuple(int(n, 16) / 255
222222
for n in [c[1:3], c[3:5], c[5:7]])
223223
+ (alpha if alpha is not None else 1.,))
224-
# hex color with alpha.
224+
# hex color in #rgb format, shorthand for #rrggbb.
225+
match = re.match(r"\A#[a-fA-F0-9]{3}\Z", c)
226+
if match:
227+
return (tuple(int(n, 16) / 255
228+
for n in [c[1]*2, c[2]*2, c[3]*2])
229+
+ (alpha if alpha is not None else 1.,))
230+
# hex color with alpha in #rrggbbaa format.
225231
match = re.match(r"\A#[a-fA-F0-9]{8}\Z", c)
226232
if match:
227233
color = [int(n, 16) / 255
228234
for n in [c[1:3], c[3:5], c[5:7], c[7:9]]]
229235
if alpha is not None:
230236
color[-1] = alpha
231237
return tuple(color)
238+
# hex color with alpha in #rgba format, shorthand for #rrggbbaa.
239+
match = re.match(r"\A#[a-fA-F0-9]{4}\Z", c)
240+
if match:
241+
color = [int(n, 16) / 255
242+
for n in [c[1]*2, c[2]*2, c[3]*2, c[4]*2]]
243+
if alpha is not None:
244+
color[-1] = alpha
245+
return tuple(color)
232246
# string gray.
233247
try:
234248
c = float(c)

lib/matplotlib/tests/test_colors.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -910,3 +910,8 @@ def __add__(self, other):
910910
def test_same_color():
911911
assert mcolors.same_color('k', (0, 0, 0))
912912
assert not mcolors.same_color('w', (1, 1, 0))
913+
914+
915+
def test_hex_shorthand_notation():
916+
assert mcolors.same_color("#123", "#112233")
917+
assert mcolors.same_color("#123a", "#112233aa")

0 commit comments

Comments
 (0)