Search code examples
pythonpython-3.xmatplotlibtransparencycolorbar

Add a custom colorbar that runs from full transparent to full color (remove artifacts)


I am trying to add a custom colorbar to my matplotlib figure, that runs from full transparent (white) to full color (mediumpurple).

I have come far, but still a few issues. The way I make this, creates lines between each patch, which are visible. This creates artifacts when I try to make the colorbar look fluent.

fig, ax = plt.subplots(figsize=(10, 10))
max_val = 4
transparency_ticks = 500
color = mpl.colors.to_rgba(color)
cmap = mpl.colors.ListedColormap([(*color[:3], (1+a)/transparency_ticks) for a in range(transparency_ticks)])
norm = mpl.colors.Normalize(vmin=0, vmax=max_val)
cax = fig.add_axes([0.8, 0.17, 0.05, 0.5])
mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm, orientation='vertical')

This is the image for transparency_ticks = 500. So you can see the lines between each patch.

Lines visible

This is the image for transparency_ticks = 5000. You don't see the lines anymore since they have blended with the rest, but these lines make the colorbar look a lot darker.

Lines make colorbar darker than it should be


Solution

  • Instead of levels onRGBA, use HSV with various saturation:

    fig, ax = plt.subplots(figsize=(10, 10))
    max_val = 4
    transparency_ticks = 50
    colors = [mpl.colors.hsv_to_rgb((0.83, a/transparency_ticks, 1)) 
              for a in range(transparency_ticks)]
    cmap = mpl.colors.ListedColormap(colors)
    norm = mpl.colors.Normalize(vmin=0, vmax=max_val)
    cax = fig.add_axes([0.8, 0.17, 0.05, 0.5])
    mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm, orientation='vertical')
    

    enter image description here