-
-
Notifications
You must be signed in to change notification settings - Fork 19k
CLN: clean color selection in _matplotlib/style #37203
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
Changes from 9 commits
0f1b99a
901453a
201b25f
8e13df5
37a820d
3883a13
f93743c
b4c3267
6af1543
31125f7
45647a4
393ae46
fe66213
1626108
79b0f08
f513bdb
76f7663
0f0f4bc
b8daf79
37734e8
765836f
4479e37
dd9efd7
f0ea701
dedd0dd
b369834
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -1,81 +1,163 @@ | ||||||
# being a bit too dynamic | ||||||
from typing import ( | ||||||
TYPE_CHECKING, | ||||||
Collection, | ||||||
Dict, | ||||||
Iterable, | ||||||
List, | ||||||
Optional, | ||||||
Sequence, | ||||||
Union, | ||||||
) | ||||||
import warnings | ||||||
|
||||||
import matplotlib.cm as cm | ||||||
import matplotlib.colors | ||||||
import numpy as np | ||||||
|
||||||
from pandas.core.dtypes.common import is_list_like | ||||||
|
||||||
import pandas.core.common as com | ||||||
|
||||||
if TYPE_CHECKING: | ||||||
from matplotlib.colors import Colormap | ||||||
|
||||||
|
||||||
Color = Union[str, Sequence[float]] | ||||||
|
||||||
|
||||||
def get_standard_colors( | ||||||
num_colors: int, colormap=None, color_type: str = "default", color=None | ||||||
num_colors: int, | ||||||
colormap=None, | ||||||
color_type: str = "default", | ||||||
color=None, | ||||||
|
||||||
): | ||||||
import matplotlib.pyplot as plt | ||||||
|
||||||
colors = _get_colors( | ||||||
color=color, | ||||||
colormap=colormap, | ||||||
color_type=color_type, | ||||||
num_colors=num_colors, | ||||||
) | ||||||
|
||||||
if isinstance(colors, dict): | ||||||
return colors | ||||||
|
||||||
return _cycle_colors(list(colors), num_colors=num_colors) | ||||||
|
||||||
|
||||||
def _get_colors( | ||||||
*, | ||||||
jreback marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
color: Optional[Union[Color, Dict[str, Color], Collection[Color]]], | ||||||
colormap: Optional[Union[str, "Colormap"]], | ||||||
color_type: str, | ||||||
num_colors: int, | ||||||
) -> Union[Dict[str, Color], Collection[Color]]: | ||||||
"""Get colors from user input.""" | ||||||
|
||||||
if color is None and colormap is not None: | ||||||
if isinstance(colormap, str): | ||||||
cmap = colormap | ||||||
colormap = cm.get_cmap(colormap) | ||||||
if colormap is None: | ||||||
raise ValueError(f"Colormap {cmap} is not recognized") | ||||||
colors = [colormap(num) for num in np.linspace(0, 1, num=num_colors)] | ||||||
return _get_colors_from_colormap(colormap, num_colors=num_colors) | ||||||
elif color is not None: | ||||||
if colormap is not None: | ||||||
warnings.warn( | ||||||
"'color' and 'colormap' cannot be used simultaneously. Using 'color'" | ||||||
) | ||||||
colors = ( | ||||||
list(color) | ||||||
if is_list_like(color) and not isinstance(color, dict) | ||||||
else color | ||||||
) | ||||||
return _get_colors_from_color(color) | ||||||
else: | ||||||
if color_type == "default": | ||||||
# need to call list() on the result to copy so we don't | ||||||
# modify the global rcParams below | ||||||
try: | ||||||
colors = [c["color"] for c in list(plt.rcParams["axes.prop_cycle"])] | ||||||
except KeyError: | ||||||
colors = list(plt.rcParams.get("axes.color_cycle", list("bgrcmyk"))) | ||||||
if isinstance(colors, str): | ||||||
colors = list(colors) | ||||||
|
||||||
colors = colors[0:num_colors] | ||||||
elif color_type == "random": | ||||||
|
||||||
def random_color(column): | ||||||
""" Returns a random color represented as a list of length 3""" | ||||||
# GH17525 use common._random_state to avoid resetting the seed | ||||||
rs = com.random_state(column) | ||||||
return rs.rand(3).tolist() | ||||||
|
||||||
colors = [random_color(num) for num in range(num_colors)] | ||||||
else: | ||||||
raise ValueError("color_type must be either 'default' or 'random'") | ||||||
return _get_colors_from_color_type(color_type, num_colors=num_colors) | ||||||
|
||||||
|
||||||
if isinstance(colors, str) and _is_single_color(colors): | ||||||
# GH #36972 | ||||||
colors = [colors] | ||||||
def _cycle_colors(colors: List[Color], num_colors: int) -> List[Color]: | ||||||
jreback marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
"""Append more colors by cycling if there is not enough color. | ||||||
# Append more colors by cycling if there is not enough color. | ||||||
# Extra colors will be ignored by matplotlib if there are more colors | ||||||
# than needed and nothing needs to be done here. | ||||||
Extra colors will be ignored by matplotlib if there are more colors | ||||||
than needed and nothing needs to be done here. | ||||||
""" | ||||||
if len(colors) < num_colors: | ||||||
try: | ||||||
multiple = num_colors // len(colors) - 1 | ||||||
except ZeroDivisionError: | ||||||
raise ValueError("Invalid color argument: ''") | ||||||
multiple = num_colors // len(colors) - 1 | ||||||
mod = num_colors % len(colors) | ||||||
|
||||||
colors += multiple * colors | ||||||
colors += colors[:mod] | ||||||
|
||||||
return colors | ||||||
|
||||||
|
||||||
def _get_colors_from_colormap( | ||||||
colormap: Union[str, "Colormap"], | ||||||
num_colors: int, | ||||||
) -> Collection[Color]: | ||||||
|
||||||
"""Get colors from colormap.""" | ||||||
colormap = _get_cmap_instance(colormap) | ||||||
return [colormap(num) for num in np.linspace(0, 1, num=num_colors)] | ||||||
|
||||||
|
||||||
def _get_cmap_instance(colormap: Union[str, "Colormap"]) -> "Colormap": | ||||||
"""Get instance of matplotlib colormap.""" | ||||||
if isinstance(colormap, str): | ||||||
cmap = colormap | ||||||
colormap = cm.get_cmap(colormap) | ||||||
if colormap is None: | ||||||
raise ValueError(f"Colormap {cmap} is not recognized") | ||||||
return colormap | ||||||
|
||||||
|
||||||
def _get_colors_from_color( | ||||||
color: Union[Color, Dict[str, Color], Collection[Color]], | ||||||
) -> Union[Dict[str, Color], Collection[Color]]: | ||||||
|
||||||
"""Get colors from user input color.""" | ||||||
if isinstance(color, Iterable) and len(color) == 0: | ||||||
raise ValueError("Invalid color argument: {color}") | ||||||
|
||||||
|
||||||
if isinstance(color, dict): | ||||||
return color | ||||||
|
||||||
if isinstance(color, str): | ||||||
if _is_single_color(color): | ||||||
# GH #36972 | ||||||
return [color] | ||||||
else: | ||||||
return list(color) | ||||||
|
||||||
# ignoring mypy error here | ||||||
# error: Argument 1 to "list" has incompatible type | ||||||
# "Union[Sequence[float], Collection[Union[str, Sequence[float]]]]"; | ||||||
# expected "Iterable[Union[str, Sequence[float]]]" [arg-type] | ||||||
# A this point color may be sequence of floats or series of colors, | ||||||
# all convertible to list | ||||||
return list(color) # type: ignore [arg-type] | ||||||
|
return list(color) # type: ignore [arg-type] | |
return list(color) # type: ignore[arg-type] |
but please avoid using ignore instead.
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
List should be enough
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
List should be enough
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
in the original code, seems there is a check of colors
in this branch, so does it mean after this refactoring, this won't happen? or colors
shouldn't be a str in the first place once reaching this part of code?
if isinstance(colors, str):
colors = list(colors)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Right, in this particular function colors will not be a string. This check is effectively carried out in _get_colors_from_color
.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
since you are doing the refactor here, maybe can you annotate this as well?