Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying python colormaps to single value beyond a specific point

How do I change a colormap color scheme to show the same color beyond a point.

E.g. here's my colormap:

import palettable
cmap = palettable.colorbrewer.sequential.YlGn_9.mpl_colormap

If I use this colormap to plot a range from 0 to 100, how can I modify the color map such that beyond 50, it changes to the color red?

like image 500
user308827 Avatar asked Aug 18 '16 17:08

user308827


People also ask

What is a mappable Matplotlib?

A colorbar needs a "mappable" ( matplotlib. cm. ScalarMappable ) object (typically, an image) which indicates the colormap and the norm to be used. In order to create a colorbar without an attached image, one can instead use a ScalarMappable with no associated data.

How do you color a line in Python?

The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument.


2 Answers

You could create the colormap for the given range (0 →100) by stacking two different colormaps on top of each other as shown:

Illustration:

import numpy as np
import matplotlib.pyplot as plt
import palettable
import matplotlib.colors as mcolors

# Set random seed
np.random.seed(42)

# Create random values of shape 10x10
data = np.random.rand(10,10) * 100 

# Given colormap which takes values from 0→50
colors1 = palettable.colorbrewer.sequential.YlGn_9.mpl_colormap(np.linspace(0, 1, 256))
# Red colormap which takes values from 50→100
colors2 = plt.cm.Reds(np.linspace(0, 1, 256))

# stacking the 2 arrays row-wise
colors = np.vstack((colors1, colors2))

# generating a smoothly-varying LinearSegmentedColormap
cmap = mcolors.LinearSegmentedColormap.from_list('colormap', colors)

plt.pcolor(data, cmap=cmap)
plt.colorbar()
# setting the lower and upper limits of the colorbar
plt.clim(0, 100)

plt.show()

Image1

Incase you want the upper portion to be of the same color and not spread over the length of the colormap, you could make the following modification:

colors2 = plt.cm.Reds(np.linspace(1, 1, 256))

Image2

like image 178
Nickil Maveli Avatar answered Nov 03 '22 01:11

Nickil Maveli


cmap.set_over("red")

And you may wanna use one of the norm functions to set your specific bounds. If using imshow, you can also set the parameter vmin=50 to make that your top value.

like image 3
story645 Avatar answered Nov 03 '22 00:11

story645