Python - Plotting colored grid based on values

前端 未结 2 1855
春和景丽
春和景丽 2020-12-08 21:47

I have been searching here and on the net. I found somehow close questions/answers to what I want, but still couldn\'t reach to what I\'m looking for.

I have an arra

2条回答
  •  不知归路
    2020-12-08 22:06

    You can create a ListedColormap for your custom colors and color BoundaryNorms to threshold the values.

    import matplotlib.pyplot as plt
    from matplotlib import colors
    import numpy as np
    
    data = np.random.rand(10, 10) * 20
    
    # create discrete colormap
    cmap = colors.ListedColormap(['red', 'blue'])
    bounds = [0,10,20]
    norm = colors.BoundaryNorm(bounds, cmap.N)
    
    fig, ax = plt.subplots()
    ax.imshow(data, cmap=cmap, norm=norm)
    
    # draw gridlines
    ax.grid(which='major', axis='both', linestyle='-', color='k', linewidth=2)
    ax.set_xticks(np.arange(-.5, 10, 1));
    ax.set_yticks(np.arange(-.5, 10, 1));
    
    plt.show()
    

    Resulting in;

    For more, you can check this matplotlib example.

提交回复
热议问题