pythonmatplotlibcolormap

The difference between ListedColormap and LinearSegmentedColormap


I print two similar commands of matplotlib colormaps, as shown below

import matplotlib as mpl
from matplotlib.colors import LinearSegmentedColormap, ListedColormap
print(mpl.colormaps['viridis'].resampled(100))
print(mpl.colormaps['copper'].resampled(100))

The first result is ListedColormap object and the second result is LinearSegmentedColormap .

I know there are quite few differences between these two objects, but I can't make clear why it gives the different kinds of objects.

Could anyone explain that?


Solution

  • mpl.colormaps['viridis'] returns a ListedColormap object: viridis is a predefined colormap in Matplotlib that is stored as a ListedColormap. A ListedColormap is essentially a list of colors that define the colormap. This means that it's a discrete colormap with a predefined set of colors, and it doesn't interpolate between colors. When you resample it, you get another ListedColormap object.

    mpl.colormaps['copper'] returns a LinearSegmentedColormap object: copper is another predefined colormap in Matplotlib, but it is stored as a LinearSegmentedColormap. A LinearSegmentedColormap is a continuous colormap that can be defined with a set of control points, allowing for interpolation between colors. When you resample it, you also get a LinearSegmentedColormap object.

    So, the difference in the type of object returned is due to how these colormaps are originally defined. viridis is discrete, while copper is continuous. When you resample them, they retain their original characteristics, resulting in different types of colormap objects.