6

I've searched around and found things that came close to working but nothing exactly suiting what I need.

Basically, I really like the viridis colormap as a starting point. However, I would like to replace the purple at the lowest end of the map with white.

I tried using set_under() but that doesn't suite my needs. I need to simply replace purple with white.

For example, I tried the following (from here Matplotlib discrete colorbar) -

cmap = plt.get_cmap('jet')
cmaplist = [cmap(i) for i in range(cmap.N)]
cmaplist[0] = (1.0,1.0,1.0,1.0)
cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)

Which works perfectly and does exactly what I need with 'jet' but when I replace 'jet' with 'viridis' I get the following error

AttributeError: 'ListedColormap' object has no attribute 'from_list'

How can I get around this and simply do what I want?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
HelloKitty
  • 61
  • 1
  • 2

1 Answers1

8

The from_list() method is a static method of the LinearSegmentedColormap class. It may not make too much sense to call it on an instance of the class, as you do in case of the jet map (although it does work of course).

Now, 'viridis' is implemented as a ListedColormap instead of a LinearSegmentedColormap, which implies that it does not have this method.

In any case it makes more sense to call the static method from the class itself.

import matplotlib.colors

cmap = plt.cm.viridis
cmaplist = [cmap(i) for i in range(cmap.N)]
cmaplist[0] = (1.0,1.0,1.0,1.0)
cmap = matplotlib.colors.LinearSegmentedColormap.from_list('mcm',cmaplist, cmap.N)

In this way, it will work for just any colormap, not only those which are segmented ones.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712