zezo
zezo

Reputation: 455

Edit colorbar by increasing one of the color range

import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19680801)

plt.subplot(111)
plt.imshow(np.random.random((100, 100)), cmap=plt.cm.BuPu_r)

plt.subplots_adjust(bottom=0.1, right=0.8, top=0.9)
cax = plt.axes([0.85, 0.1, 0.075, 0.8])
plt.colorbar(cax=cax)
plt.show()

In the above example, how do I edit the colormap to increase the violet color? Something like biased to violet.

Upvotes: 0

Views: 207

Answers (1)

JohanC
JohanC

Reputation: 80279

Here are two examples to change the colormap. At the left, the orinal version is shown. In the center, the 60% of the lower colors is used. At the right, the colors near purple are sampled more, and the colors at the top less.

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

np.random.seed(19680801)
data = np.random.random((100, 100))

fig, axs = plt.subplots(ncols=3, figsize=(15, 5))

for ax in axs.flat:
    if ax == axs[0]:
        cmap = plt.cm.BuPu_r
        ax.set_title('"BuPu_r" color map')
    elif ax == axs[1]:
        cmap = ListedColormap(plt.cm.BuPu_r(np.linspace(0, 0.6, 256)))
        ax.set_title('60% lower subset of the color map')
    else:
        cmap = ListedColormap(plt.cm.BuPu_r(np.linspace(0, 1, 256) ** 2))
        ax.set_title('expanding lower part and\ncompressing upper part')
    img = ax.imshow(data, cmap=cmap)
    plt.colorbar(img, shrink=0.8, ax=ax)
plt.tight_layout()
plt.show()

comparing cmaps

plt.cm.BuPu_r is a function that, given a value between 0 and 1, returns the corresponding color. np.linspace(0, 0.6, 256) divides the range from 0 to 0.6 into 256 parts, returning an array of 256 equally spaced values [0, ..., 0.6]. Calling the colormap with this array as input, returns an array of 256 corresponding colors. Calling ListedColormap(...) with an array of 256 colors creates a new colormap with these colors (a colormap gives a color for input values between 0 and 1).

np.linspace(0, 1, 256)**2) returns an array of 256 equally spaced values between 0 and 1, and takes the square of each individual value. So, instead of being equally spaced, they are now compressed towards 0. (A higher power than 2 would compress more, a power between 2 and 1 would compress less). Using this array of values as input for the colormap gives an array of colors, but the colors will be closer to purple.

More information can be found in the colormap tutorial.

Upvotes: 1

Related Questions