Search code examples
pythonmatplotlibtransparencycolorbar

How to set pcolor savefig colorbar transparency


I am trying to export a pcolor figure with a colorbar. The cmap of the colorbar has a transparent color. The exported figure has transparent colors in the axes but not in the colorbar. How can I fix this?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

x = np.random.random((10, 10))
colors = [(0,0,0,0), (0,0,0,1)]
cm = LinearSegmentedColormap.from_list('custom', colors, N=256, gamma=0)
plt.pcolor(x,cmap=cm)
plt.colorbar()
plt.savefig('figure.pdf',transparent=True)

I put the image against a grey background to check. As can be seen, the cmap in the axes is transparent while the one in the colorbar is not.

I put the image against a grey background to check. As can be seen, the cmap in the axes is transparent while the one in the colorbar is not


Solution

  • While the colorbar resides inside an axes, it has an additional background patch associated with it. This is white by default and will not be taken into account when transparent=True is used inside of savefig.

    A solution is hence to remove the facecolor of this patch manually,

    cb.patch.set_facecolor("none")
    

    A complete example, which shows this without actually saving the figure

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.colors import LinearSegmentedColormap
    
    x = np.random.random((10, 10))
    colors = [(1,1,1,0), (0,0,0,1)]
    cm = LinearSegmentedColormap.from_list('custom', colors, N=256, gamma=0)
    
    fig, ax = plt.subplots(facecolor="grey")
    
    im = ax.pcolor(x,cmap=cm)
    cb = fig.colorbar(im, drawedges=False)
    
    ax.set_facecolor("none")
    cb.patch.set_facecolor("none")
    
    plt.show()
    

    enter image description here