A.Razavi
A.Razavi

Reputation: 509

How to obtain RGB values for matplotlib color schemes?

How can I get these example cdict values (https://matplotlib.org/2.0.1/examples/pylab_examples/custom_cmap.html):

cdict = {'red':   ((0.0,  0.0, 0.0),
               (0.5,  1.0, 1.0),
               (1.0,  1.0, 1.0)),

     'green': ((0.0,  0.0, 0.0),
               (0.25, 0.0, 0.0),
               (0.75, 1.0, 1.0),
               (1.0,  1.0, 1.0)),

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

for the bwr color scheme (https://matplotlib.org/examples/color/colormaps_reference.html) in matplotlib?

Upvotes: 1

Views: 6082

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339745

To answer the question, the colors for the "bwr" colormap can be obtained via

import matplotlib.cm
print(matplotlib.cm.datad["bwr"])

which prints

((0.0, 0.0, 1.0), (1.0, 1.0, 1.0), (1.0, 0.0, 0.0))

and that is simply ["blue", "white", "red"].

This may not be too useful for the actual application though. To create a colormap with a wider range of white in the middle, best create the colormap from a list of colors, and possibly their respective values.

To this end, the LinearSegmentedColormap.from_list method can be used.

from matplotlib.colors import LinearSegmentedColormap

colors = [(0, "blue"), (0.4, "white"), (0.6, "white"), (1, "red")]
cmap = LinearSegmentedColormap.from_list("bwwr", colors)

The numbers are between 0 and 1, need to be ascending and denote the "position" of that respecitive color. The above would create a colormap with a gradient from blue to white between 0 and 0.4, then all white between 0.4 and 0.6, then a gradient from white to red between 0.6 and 1.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

colors = [(0, "blue"), (0.4, "white"), (0.6, "white"), (1, "red")]
cmap = LinearSegmentedColormap.from_list("bwwr", colors)

a = np.arange(0,100).reshape(10,10)

fig, (ax,ax2) = plt.subplots(ncols=2, figsize=(7,3))
im = ax.imshow(a, cmap="bwr")
fig.colorbar(im, ax=ax)
im2 = ax2.imshow(a, cmap=cmap)
fig.colorbar(im2, ax=ax2)

ax.set_title("bwr")
ax2.set_title("bwwr")
plt.show()

enter image description here

Upvotes: 2

Related Questions