Skip to content

Commit 1ca57ed

Browse files
Michael Vincent ManninoMichael Vincent Mannino
authored andcommitted
same colors for <= 7, then random
1 parent e9511d0 commit 1ca57ed

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

pandas/plotting/_matplotlib/core.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1342,7 +1342,7 @@ def _make_plot(self, fig: Figure) -> None:
13421342
# colored by uniqueness of the strings, such same strings get same color
13431343
create_colors = not self._are_valid_colors(c_values)
13441344
if create_colors:
1345-
color_mapping, c_values = self._uniquely_color_strs(c_values)
1345+
custom_color_mapping, c_values = self._uniquely_color_strs(c_values)
13461346
cb = False # no colorbar; opt for legend
13471347

13481348
if self.legend:
@@ -1380,7 +1380,7 @@ def _make_plot(self, fig: Figure) -> None:
13801380
ax.legend(
13811381
handles=[
13821382
mpl.patches.Circle((0, 0), facecolor=color, label=string)
1383-
for string, color in color_mapping.items()
1383+
for string, color in custom_color_mapping.items()
13841384
]
13851385
)
13861386

@@ -1408,7 +1408,7 @@ def _get_c_values(self, color, color_by_categorical: bool, c_is_column: bool):
14081408
return c_values
14091409

14101410
def _are_valid_colors(self, c_values: np.ndarray | list):
1411-
# check if c_values contains strings and if these strings are valid mpl colors
1411+
# check if c_values contains strings and if these strings are valid mpl colors.
14121412
# no need to check numerics as these (and mpl colors) will be validated for us
14131413
# in .Axes.scatter._parse_scatter_color_args(...)
14141414
try:
@@ -1424,10 +1424,16 @@ def _uniquely_color_strs(
14241424
self, c_values: np.ndarray | list
14251425
) -> tuple[dict, np.ndarray]:
14261426
# well, almost uniquely color them (up to 949)
1427-
possible_colors = list(mpl.colors.XKCD_COLORS.values()) # Hex representations
1428-
shuffle(possible_colors) # TODO: find better way of getting colors
1429-
14301427
unique = np.unique(c_values)
1428+
1429+
# for up to 7, lets keep colors consistent
1430+
if len(unique) <= 7:
1431+
possible_colors = list(mpl.colors.BASE_COLORS.values()) # Hex
1432+
# explore better ways to handle this case
1433+
else:
1434+
possible_colors = list(mpl.colors.XKCD_COLORS.values()) # Hex
1435+
shuffle(possible_colors)
1436+
14311437
colors = [possible_colors[i % len(possible_colors)] for i in range(len(unique))]
14321438
color_mapping = dict(zip(unique, colors))
14331439

0 commit comments

Comments
 (0)