1

I want to reverse my custom colormap which looks like this

import matplotlib.cm as cm
import matplotlib as mpl

cm.register_cmap(name='owb',
    data = {'red':      ((0.0, 1.0, 1.0),  # orange
                        (0.5, 1.0, 1.0),  #
                        (1.0, 0.0, 0.0)), # blue

            'green':    ((0.0, 0.6, 0.6),  # orange
                        (0.5, 1.0, 1.0),  #
                        (1.0, 0.0, 0.0)), # blue

             'blue':    ((0.0, 0.0, 0.0),  # orange
                        (0.5, 1.0, 1.0),  #
                        (1.0, 1.0, 1.0))  # blue
            })

Now since I am searching for a solution to this for quite some time and while doing so I came across this thread:

colormap reversed

I tried to use .reversed() here:

data = {'red':      ((0.0, 1.0, 1.0),  # orange
                        (0.5, 1.0, 1.0),  #
                        (1.0, 0.0, 0.0)), # blue

            'green':    ((0.0, 0.6, 0.6),  # orange
                        (0.5, 1.0, 1.0),  #
                        (1.0, 0.0, 0.0)), # blue

             'blue':    ((0.0, 0.0, 0.0),  # orange
                        (0.5, 1.0, 1.0),  #
                        (1.0, 1.0, 1.0))  # blue
            }
owb = mpl.colors.ListedColormap('OrWhBlu', data)
owb_reversed = owb.reversed()

Here I got the following Error:

TypeError: unsupported operand type(s) for +: 'dict' and 'str'

but I just didn't manage to make it work.

Please let me know what I am doing wrong.
Cheers

EDIT: I tried the solution of Kostas, and since i have to use the colormap_r in another function where the name of the cmap is required I tried to solve it this way:

cmap_r = cm.register_cmap(name="owb_r", cmap=owb_r)

the function where it is called:

plt.pcolormesh(xx, yy, -Z, cmap="owb_r")
plt.scatter(X_2d[:, 0], X_2d[:, 1], c=y_2d, cmap="owb_r",
            edgecolors='k')

now i get following Error: ValueError: Invalid RGBA argument: 'u'

CRoNiC
  • 329
  • 2
  • 4
  • 14
  • What is the expected output? (How does the reversed data look like?) – balderman Oct 24 '19 at 08:47
  • good question, I tried reversing the numbers in the dict manualy but it didn't do what I wanted it to do. The standart cmaps always have a cmap_r and thats what I try to achieve. – CRoNiC Oct 24 '19 at 08:48

1 Answers1

1

You need a LinearSegmentedColormap, not a ListedColormap. Then you need to register the reversed() version of it.

import numpy as np
import matplotlib.cm as cm
import matplotlib as mpl
import matplotlib.pyplot as plt

colors = [(1.0, 0.6, 0.0), "white","blue"]
cm.register_cmap(cmap=mpl.colors.LinearSegmentedColormap.from_list("owb", colors).reversed())


fig, ax = plt.subplots()
im = ax.imshow(np.random.rand(12,12), cmap="owb_r")
fig.colorbar(im)

plt.show()  
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712