Skip to content

Add method for comparing two colors #10032

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 21, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 30 additions & 3 deletions lib/matplotlib/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,38 @@ def is_color_like(c):
return True


def same_color(c1, c2):
"""
Compare two colors to see if they are the same.

Parameters
----------
c1, c2 : Matplotlib colors

Returns
-------
bool
``True`` if *c1* and *c2* are the same color, otherwise ``False``.
"""
return (to_rgba_array(c1) == to_rgba_array(c2)).all()


def to_rgba(c, alpha=None):
"""Convert *c* to an RGBA color.
"""
Convert *c* to an RGBA color.

If *alpha* is not *None*, it forces the alpha value, except if *c* is
``"none"`` (case-insensitive), which always maps to ``(0, 0, 0, 0)``.
Parameters
----------
c : Matplotlib color

alpha : scalar, optional
If *alpha* is not ``None``, it forces the alpha value, except if *c* is
``"none"`` (case-insensitive), which always maps to ``(0, 0, 0, 0)``.

Returns
-------
tuple
Tuple of ``(r, g, b, a)`` scalars.
"""
# Special-case nth color syntax because it should not be cached.
if _is_nth_color(c):
Expand Down
5 changes: 5 additions & 0 deletions lib/matplotlib/tests/test_colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -715,3 +715,8 @@ def __add__(self, other):
else:
assert len(recwarn) == 0
recwarn.clear()


def test_same_color():
assert mcolors.same_color('k', (0, 0, 0))
assert not mcolors.same_color('w', (1, 1, 0))