Reputation: 6290
I have the following 3x3 matrix which I would like to plot:
import matplotlib.cm
import matplotlib.pyplot as plt
import numpy as np
import copy
cmap = copy.copy(cm.get_cmap("Blues"))
cmap.set_bad('white')
fig = plt.figure(figsize=(15, 10))
img = np.array([[-0.9, -0.5599234, 0.21042876],[-0.42735877, 0.61514954, -0.74305015],[0.61958201, -0.04358633, 0.78672511]])
im = plt.imshow(img, origin='upper', cmap=cmap)
The result looks as follows:
As visible the top left entry is smallest and should be displayed as white. How can I change it in such a way so that the smallest entry is displayed in white?
Second, is there a way to adapt the colormap such that it starts with darker values?
Upvotes: 1
Views: 4294
Reputation: 80544
One way to have a colormap start with white, is to create a ListedColormap
, e.g. going from white
to darkblue
. To start with the darkest color, just reverse the list of colors for the ListedColormap
.
A standard colormap can be reversed, just by appending _r
at the end of its name.
One way to create a colormap going from a mid-range to a dark blue, is creating a ListedColormap
where the rgb-values are given as hexadecimal.
Here are some examples:
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np
img = np.array([[-0.9, -0.5599234, 0.21042876], [-0.42735877, 0.61514954, -0.74305015], [0.61958201, -0.04358633, 0.78672511]])
fig, axs = plt.subplots(ncols=3, figsize=(12, 5))
cmap0 = LinearSegmentedColormap.from_list('', ['white', 'darkblue'])
cmap1 = 'Blues_r'
cmap2 = LinearSegmentedColormap.from_list('', ['#aaddee', '#000077'])
for ax, cmap in zip(axs, [cmap0, cmap1, cmap2]):
im = ax.imshow(img, origin='upper', cmap=cmap)
plt.colorbar(im, ax=ax, orientation='horizontal', pad=0.05)
ax.set_xticks([0, 1, 2])
ax.set_yticks([0, 1, 2])
ax.tick_params(labelbottom=False, labelleft=False, length=0) # hide ticks, but use position for a grid
ax.grid(True, color='white')
axs[0].set_title("Colormap from white to darkblue")
axs[1].set_title("Reversed blues colormap")
axs[2].set_title("Custom darker blues colormap")
plt.show()
Also of interest might be Seaborn's palette functions, which provide additional ways to create colormaps (the parameter as_cmap=True
is needed for these functions to return a colormap).
Upvotes: 3