Setting Transparency Based on Pixel Values in Matplotlib

后端 未结 2 1427
悲&欢浪女
悲&欢浪女 2020-12-13 06:32

I am attempting to use matplotlib to plot some figures for a paper I am working on. I have two sets of data in 2D numpy arrays: An ascii hillshade raster which I can happily

相关标签:
2条回答
  • 2020-12-13 07:06

    An alternate way to do this with out using masked arrays is to set how the color map deals with clipping values below the minimum of clim (shamelessly using Joe Kington's example):

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    
    # Generate some data...
    gray_data = np.arange(10000).reshape(100, 100)
    
    masked_data = np.random.random((100,100))
    
    my_cmap = cm.jet
    my_cmap.set_under('k', alpha=0)
    
    
    # Overlay the two images
    fig, ax = plt.subplots()
    ax.imshow(gray_data, cmap=cm.gray)
    im = ax.imshow(masked_data, cmap=my_cmap, 
              interpolation='none', 
              clim=[0.9, 1])
    plt.show()
    

    example

    There as also a set_over for clipping off the top and a set_bad for setting how the color map handles 'bad' values in the data.

    An advantage of doing it this way is you can change your threshold by just adjusting clim with im.set_clim([bot, top])

    0 讨论(0)
  • 2020-12-13 07:16

    Just mask your "river" array.

    e.g.

    rivers = np.ma.masked_where(rivers == 0, rivers)
    

    As a quick example of overlaying two plots in this manner:

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    
    # Generate some data...
    gray_data = np.arange(10000).reshape(100, 100)
    
    masked_data = np.random.random((100,100))
    masked_data = np.ma.masked_where(masked_data < 0.9, masked_data)
    
    # Overlay the two images
    fig, ax = plt.subplots()
    ax.imshow(gray_data, cmap=cm.gray)
    ax.imshow(masked_data, cmap=cm.jet, interpolation='none')
    plt.show()
    

    enter image description here

    Also, on a side note, imshow will happily accept floats for its RGBA format. It just expects everything to be in a range between 0 and 1.

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