对称颜色图 matplotlib

AJa*_*llo 7 python matplotlib

我有一系列在 -180 到 180 之间变化的值,我是一个关于零对称的颜色图,即 -180 的颜色对于 180 值是相同的,依此类推。这是我第一次使用 matplotlib 我只是没有找到使它围绕零对称的方法,负片总是与正片具有不同的颜色。非常感谢。

小智 5

感谢以下贡献者: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
Run Code Online (Sandbox Code Playgroud)

测试它会给你:

# --- 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()
Run Code Online (Sandbox Code Playgroud)

结果图


Syl*_*ain 1

并不完美,但发散颜色图至少居中:

from matplotlib import pyplot as plt
<function using cmap>.(cmap=plt.get_cmap("PiYG"))
Run Code Online (Sandbox Code Playgroud)

CMAP 示例