Colormap with maximum distinguishable colours

后端 未结 2 429
野性不改
野性不改 2021-02-05 15:49

Using matplotlib in Python I\'m plotting anywhere between 20 and 50 lines. Using matplotlib\'s sliding colour scales these become indistinguishable after a certain number of li

2条回答
  •  伪装坚强ぢ
    2021-02-05 16:11

    Recently, I also encountered the same problem. So I created the following simple Python code to generate visually distinguishable colors for jupyter notebook matplotlib. It is not quite maximally perceptually distinguishable, but it works better than most built-in colormaps in matplotlib.

    The algorithm splits the HSV scale into 2 chunks, 1st chunk with increasing RGB value, 2nd chunk with decreasing alpha so that the color can blends into the white background.

    Take note that if you are using any toolkit other than jupyter notebook, you must make sure the background is white, otherwise, alpha blending will be different and the resultant color will also be different.

    Furthermore, the distinctiveness of color highly depends on your computer screen, projector, etc. A color palette distinguishable on one screen does not necessarily imply on another. You must physically test it out if you want to use for presentation.

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.colors import ListedColormap
    
    def generate_colormap(N):
        arr = np.arange(N)/N
        N_up = int(math.ceil(N/7)*7)
        arr.resize(N_up)
        arr = arr.reshape(7,N_up//7).T.reshape(-1)
        ret = matplotlib.cm.hsv(arr)
        n = ret[:,3].size
        a = n//2
        b = n-a
        for i in range(3):
            ret[0:n//2,i] *= np.arange(0.2,1,0.8/a)
        ret[n//2:,3] *= np.arange(1,0.1,-0.9/b)
    #     print(ret)
        return ret
    
    N = 16
    H = np.arange(N*N).reshape([N,N])
    fig = plt.figure(figsize=(10, 10))
    ax = plt.pcolor(H, cmap=ListedColormap(generate_colormap(N*N)))
    

提交回复
热议问题