Search code examples
pythonpython-3.xmatplotlibalpha-transparency

How do I use matplotlibs colormap alpha-values to make tripcolor plot fade to transparency?


I want to plot a probability distribution over a map using tripcolor and want the distribution to fade to transparency where the probability is low/zero. However tripcolor doesn't seem to accept local alpha-values provided by the colormap.

I set up a custom colormap that transitions from a transparent (alpha=0.) white to some blueish color (alpha=1.), as described in the matplotlib docs.

cdict = {'red': ((0., 1., 1.),
                 (1., 0., 0.)),
         'green': ((0., 1., 1.),
                   (1., 0.5, 0.5)),
         'blue': ((0., 1., 1.),
                  (1., 1., 1.)),
         'alpha': ((0., 0., 0.),
                   (1., 1., 1.))}
testcmap = colors.LinearSegmentedColormap('test', cdict)
plt.register_cmap(cmap=testcmap)

If I apply this to a line, as described here everything works fine.

However if I want to use tripcolor to draw the distribution, it seems to ignore the colormap alpha values...

It works for a scatter plot.

A minimal working example can be found below.

import numpy as np
from matplotlib import pyplot as plt, colors, cm

# quick and dirty test data
ext = np.linspace(0., 1., 21)
coords, _ = np.meshgrid(ext, ext)

x = coords.flatten()
y = coords.T.flatten()

vals = 1. - np.sin(coords * np.pi / 2).flatten()

# color dict
cdict = {'red': ((0., 1., 1.),
                 (1., 0., 0.)),
         'green': ((0., 1., 1.),
                   (1., 0.5, 0.5)),
         'blue': ((0., 1., 1.),
                  (1., 1., 1.)),
         'alpha': ((0., 0., 0.),
                   (1., 1., 1.))}
# colormap from dict
testcmap = colors.LinearSegmentedColormap('test', cdict)
plt.register_cmap(cmap=testcmap)
# plotting
fig, ax = plt.subplots(1)
ax.set_facecolor('black')

ax.tripcolor(x, y, vals, cmap='test')

fig2, ax2 = plt.subplots(1)
ax2.set_facecolor('black')

ax2.scatter(x, y, c=vals, cmap='test')

plt.show()

Edit: Looking at the sourcecode line 118 seems to set a global alpha for the triangulation. Copy/pasting the tripcolor function and omitting this line worked. However it would still be nice to use matplotlibs built-in functions...

Edit2: Changed the data generation function from cos to 1-sin to get a more suggestive transition. For the first edit to give a nice result I also hat to use shading='gouraud'.


Solution

  • Is this closer to what you are looking for?

    ax.tripcolor(x, y, vals, cmap='test', alpha=None)
    

    Not sure why, but my guess is that setting alpha=None allows each triangle to get the alpha color from the colormap.