Hi,
I've been trying to plot a line with varying alpha (but constant color). After much googling I have come up with the following code segment, which by all indications should work. It works when I vary an individual RGB element, but not when I vary alpha.
···
#################################################
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
# the line to plot
x = np.linspace(0,1,101)
y = x*0.5-0.25
scaling = np.exp(-(x-0.5)**2/0.5**2) # scale the transparency of the line according to this
# Create a colormap which has a constant color, but varies the transparency.
N = 50 # this many different transparency levels
alpha_boundaries = np.linspace(np.min(scaling),np.max(scaling),N+1)
# The lowest values are transparent, the highest ones are opaque
cmap = ListedColormap([(0.0,0.0,0.0,a) for a in np.linspace(0,1,N)])
norm = BoundaryNorm(alpha_boundaries, cmap.N)
# Create a set of line segments so that we can color them individually
# This creates the points as a N x 1 x 2 array so that we can stack points
# together easily to get the segments. The segments array for line collection
# needs to be numlines x points per line x 2 (x and y)
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
# Create the line collection object, setting the colormapping parameters.
# Have to set the actual values used for colormapping separately.
lc = LineCollection(segments, cmap=cmap, norm=norm)
lc.set_array(scaling)
ax = plt.subplot(111)
ax.add_collection(lc)
plt.xlim(x.min(), x.max())
plt.ylim(y.min(), y.max())
plt.show()
#################################################
What appears to be happening is that the alpha values in the cmap I use when I create the ListedColormap object are being ignored by the add_collection function. I see that this bug (or something quite like it) was reported in late 2008:
http://matplotlib.1069221.n5.nabble.com/create-ListedColormap-with-different-alpha-values-tt18693.html#a18697
Did the patch from late 2008 not make it into the code, or has this bug resurfaced? Does anyone know of a workaround for this issue?
Cheers,
Oliver