Making figure transparent with colored background

后端 未结 3 1944
隐瞒了意图╮
隐瞒了意图╮ 2021-01-12 18:09

I have a bit of a situation. What I need is a plot with a black background with several white circles drawn on top of that black background.

I managed to do this usi

3条回答
  •  -上瘾入骨i
    2021-01-12 18:35

    Circles masked with colorbar

    Colormaps can have an alpha channel, so if your data is on a mesh with high vs low values showing circle vs not-circle, one set of those values can be transparent.

    This only works for me when saving the figure programmatically, with the transparent keyword; not from the Python image window.

    Starting from one of the matplotlib gallery examples (in a gimp-alike, I can cut & paste segments and the transparency is right):

    # plot transparent circles with a black background
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.colors import LinearSegmentedColormap
    from matplotlib.cm import Greys
    
    
    dark_low = ((0., 1., 1.),
             (.3, 1., 0.),
             (1., 0., 0.))
             
    cdict = {'red':  dark_low,
    
         'green': dark_low,
    
         'blue': dark_low}
    
    cdict3 = {'red':  dark_low,
    
         'green': dark_low,
    
         'blue': dark_low,
                   
         'alpha': ((0.0, 0.0, 0.0),
                   (0.3, 0.0, 1.0),
                   (1.0, 1.0, 1.0))
        }
    
    greys = LinearSegmentedColormap('Greys', cdict)
    plt.register_cmap(cmap=greys)
        
    dropout_high = LinearSegmentedColormap('Dropout', cdict3)
    plt.register_cmap(cmap = dropout_high)
    
    # Make some illustrative fake data:
    
    x = np.arange(0, np.pi, 0.1)
    y = np.arange(0, 2*np.pi, 0.1)
    X, Y = np.meshgrid(x,y)
    Z = np.cos(X) * np.sin(Y) * 10
    
    # Make the figure:
    
    plt.figure()
    plt.subplot(1,3,1)
    plt.imshow(Z, cmap=Greys)
    plt.title('Smooth\ncolorbar')
    plt.colorbar()
    plt.subplot(1,3,2)
    plt.imshow(Z, cmap=greys)
    plt.title('Linear\ncolorbar')
    plt.colorbar()
    plt.subplot(1,3,3)
    plt.imshow(Z, cmap = dropout_high)
    plt.title('Alpha crops\n colorbar')
    plt.colorbar()
    plt.savefig('dropout_cmap', transparent=True)
    

    Adapting colorbar to a alpha-channel visual mask

    And as a layer over another image. Interesting, the colorbar with alpha channel doesn't have transparency. That seems like a bug.

    Plots with and without alpha-channel over another image

提交回复
热议问题