Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symmetric colormap matplotlib

I have a series of values that varies between -180 to 180, I what a color map symmetric around zero, i.e. the color for -180 is the same for 180 values and so on. It is my first time using matplotlib I only don't find the way to make it symmetric around zero, the negatives always have different colors that the positives. Thank you very much.

like image 832
AJaramillo Avatar asked Feb 10 '15 18:02

AJaramillo


People also ask

What is Matplotlib colormap?

Scientifically, the human brain perceives various intuition based on the different colors they see. Matplotlib provides some nice colormaps you can use, such as Sequential colormaps, Diverging colormaps, Cyclic colormaps, and Qualitative colormaps.

What is Matplotlib default colormap?

Colormap. The new default colormap used by matplotlib. cm. ScalarMappable instances is 'viridis' (aka option D).

How do you normalize a Colorbar in Python?

norm = normi; #mpl. colors. Normalize(vmin=-80, vmax=20); plt. axis([1, 1000, -400, 400]);


2 Answers

Thanks to the contribution from : https://stackoverflow.com/a/31052741

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


def symmetrical_colormap(cmap_settings, new_name = None ):
    ''' This function take a colormap and create a new one, as the concatenation of itself by a symmetrical fold.
    '''
    # get the colormap
    cmap = plt.cm.get_cmap(*cmap_settings)
    if not new_name:
        new_name = "sym_"+cmap_settings[0]  # ex: 'sym_Blues'
    
    # this defined the roughness of the colormap, 128 fine
    n= 128 
    
    # get the list of color from colormap
    colors_r = cmap(np.linspace(0, 1, n))    # take the standard colormap # 'right-part'
    colors_l = colors_r[::-1]                # take the first list of color and flip the order # "left-part"

    # combine them and build a new colormap
    colors = np.vstack((colors_l, colors_r))
    mymap = mcolors.LinearSegmentedColormap.from_list(new_name, colors)

    return mymap

And testing it gives you :

# --- Quick test -------------------------
cmap_settings = ('Blues', None)  # provide int instead of None to "discretize/bin" the colormap
mymap = symmetrical_colormap(cmap_settings= cmap_settings, new_name =None )

data = np.random.rand(10,10) * 2 - 1
plt.pcolor(data, cmap=mymap)
plt.colorbar()
plt.show()

Result_figure

like image 141
GentilsTo Avatar answered Oct 18 '22 01:10

GentilsTo


Not perfect, but the Diverging colormaps are at least centered:

from matplotlib import pyplot as plt
<function using cmap>.(cmap=plt.get_cmap("PiYG"))

cmaps examples

like image 20
Sylvain Avatar answered Oct 18 '22 02:10

Sylvain