Tag Archives: Viridis

Reversing a matplotlib colormap

I wanted to try to test out the new Matplotlib colormap viridis:

Matplotlib Viridis colormap

Initially, I couldn’t find an easy way to use it since it isn’t in the current version (1.4.3).  I found the underlying data list it in “_cm_listed.py” in the Matplotlib Github listed as “_viridis_data”and built the colormap from the data list:

viridis_cm = LinearSegmentedColormap.from_list('viridis', cm_data)

Here is the figure I was working on with the viridis colormap:

Looking at the figure, what I really wanted was the reverse of the colormap. Since I wasn’t using one of the listed Matplotlib colormaps, I couldn’t use the “_r” try to reverse it (i.e. to invert “jet” use “jet_r” instead). I I looked around for awhile for a simple method to reverse the colormap but didn’t find any really helpful stackoverflow posts. Finally, after digging around in the Matplotlib help I noticed the revcmap function. From there it was simply a matter of calling the function on the extracted colormap data.

viridis_r_cm = matplotlib.colors.LinearSegmentedColormap(
    'viridis_r', matplotlib.cm.revcmap(viridis_cm._segmentdata))

The figure still doesn’t look great but it is the reverse: