Skip to content

[Bug]: matplotlib.colors.LinearSegmentedColormap.from_list doesn't work with hex representation of colors #27029

@jose-vines-toteat

Description

@jose-vines-toteat

Bug summary

For some reason colors.LinearSegmentedColormap.from_list stopped working with colors such as '#E3DBCC', when in previous versions it used to work.

It raises an error in to_rgba_array(colors), but when actually calling colors.to_rgba_array(['#E3DBCC']) it works just fine.

Code for reproduction

import matplotlib.colors as colors
start = '#E3DBCC'
end = '#FF4B33'

color_list = [(0, start), (1, end)]
my_cmap = colors.LinearSegmentedColormap.from_list('my_cmap', color_list)

Actual outcome

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[12], line 6
      3 end = '#FF4B33'
      5 color_list = [(0, start), (1, end)]
----> 6 my_cmap = colors.LinearSegmentedColormap.from_list('my_cmap', color_list)

File ~/mambaforge/envs/tf/lib/python3.9/site-packages/matplotlib/colors.py:1065, in LinearSegmentedColormap.from_list(name, colors, N, gamma)
   1062 else:
   1063     vals = np.linspace(0, 1, len(colors))
-> 1065 r, g, b, a = to_rgba_array(colors).T
   1066 cdict = {
   1067     "red": np.column_stack([vals, r, r]),
   1068     "green": np.column_stack([vals, g, g]),
   1069     "blue": np.column_stack([vals, b, b]),
   1070     "alpha": np.column_stack([vals, a, a]),
   1071 }
   1073 return LinearSegmentedColormap(name, cdict, N, gamma)

File ~/mambaforge/envs/tf/lib/python3.9/site-packages/matplotlib/colors.py:489, in to_rgba_array(c, alpha)
    487         raise e
    488 if isinstance(c, str):
--> 489     raise ValueError(f"{c!r} is not a valid color value.")
    491 if len(c) == 0:
    492     return np.zeros((0, 4), float)

ValueError: '#E3DBCC' is not a valid color value.

Expected outcome

I expect the LinearSegmentedColormap to be created successfully.

Additional information

No response

Operating system

OS X 13.1

Matplotlib Version

3.8.0

Matplotlib Backend

'module://matplotlib_inline.backend_inline'

Python version

3.9

Jupyter version

3.6.1

Installation

conda

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions