Reset default matplotlib colormap values after using 'set_under' or 'set_over'

前端 未结 1 452
独厮守ぢ
独厮守ぢ 2021-01-03 01:22

This is something that has been bugging me for a while. Whenever I use the cmap.set_under() or cmap.set_over() methods to change the the color of o

相关标签:
1条回答
  • 2021-01-03 02:10

    The behaviour you describe is expected. There is only a single colormap present, which is plt.cm.rainbow. When you first set_under('w') and later set_under('k'), the color for under will be black.

    What you want to do is actually use two different instances of the same colormap and then change each instance to have a different value for the lower bound.
    This can easily be done using copy,

    cmap1 = copy.copy(plt.cm.rainbow)
    

    Now manipulating cmap1 does not change the rainbow colormap itself, such that it is possible to later create another copy of it and apply different settings.

    import matplotlib.pyplot as plt 
    import numpy as np
    import copy
    
    rand_data = np.random.randint(50, size=(20,20))
    
    plt.figure()
    plt.subplot(211)
    cmap1 = copy.copy(plt.cm.rainbow)
    im1 = plt.pcolormesh(rand_data, cmap=cmap1, vmin=10)
    im1.cmap.set_under('w')
    plt.colorbar(extend='min')
    
    plt.subplot(212)
    cmap2 = copy.copy(plt.cm.rainbow)
    im2 = plt.pcolormesh(rand_data, cmap=cmap2, vmin=10)
    im2.cmap.set_under('k')
    plt.colorbar(extend='min')
    
    plt.show()
    

    0 讨论(0)
提交回复
热议问题