Skip to content

Commit b91e635

Browse files
Michael Vincent ManninoMichael Vincent Mannino
authored andcommitted
convert non numericals and color strings to valid colors
1 parent d966462 commit b91e635

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

pandas/plotting/_matplotlib/core.py

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1388,7 +1388,37 @@ def _get_c_values(self, color, color_by_categorical: bool, c_is_column: bool):
13881388
c_values = self.data[c].values
13891389
else:
13901390
c_values = c
1391-
return c_values
1391+
1392+
return self._prevalidate_c_values(c_values)
1393+
1394+
def _prevalidate_c_values(self, c_values):
1395+
# if c_values contains strings, pre-check whether these are valid mpl colors
1396+
# should we determine c_values are valid to this point, no changes are made
1397+
# to the object
1398+
1399+
# check if c_values contains strings. no need to check numerics as these
1400+
# will be validated for us in .Axes.scatter._parse_scatter_color_args(...)
1401+
if not (
1402+
np.iterable(c_values) and len(c_values) > 0 and isinstance(c_values[0], str)
1403+
):
1404+
return c_values
1405+
1406+
try:
1407+
_ = mpl.colors.to_rgba_array(c_values)
1408+
1409+
# similar to above, if this conversion is successful, remaining validation
1410+
# will be done in .Axes.scatter._parse_scatter_color_args(...)
1411+
return c_values
1412+
1413+
except (TypeError, ValueError) as _:
1414+
# invalid color strings, build numerics based off this
1415+
# map N unique str to N evenly spaced values [0, 1], colors
1416+
# will be automattically assigned based off this mapping
1417+
unique = np.unique(c_values)
1418+
colors = np.linspace(0, 1, len(unique))
1419+
color_mapping = dict(zip(unique, colors))
1420+
1421+
return np.array(list(map(color_mapping.get, c_values)))
13921422

13931423
def _get_norm_and_cmap(self, c_values, color_by_categorical: bool):
13941424
c = self.c

0 commit comments

Comments
 (0)