This is not a duplicate of Add alpha to an existing matplotlib colormap because that question was vague, and the only answer incorporates the alpha into the colormap (meaning color and alpha are inexorably tied together).
In my example, alpha and color are determined from two different channels of information.
Edit: The second proposed duplicate link has a valid solution, so no need to reopen.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
x = np.linspace(0, 10)
y = np.cos(x)
value = 10 * np.cos(x / 3)
alpha = y**2
fig, ax = plt.subplots(figsize=(4, 3))
I want to apply a colormap to value
, and use individual alphas for each point. I also want a colorbar. Plotting a colorbar with no alpha is easy:
ax.set(title='plot with correct colorbar')
scatter = ax.scatter(x, y, c=value, cmap='hsv')
fig.colorbar(scatter)
Adding individual alphas in scatter
is possible if you supply RGBA data for c
(the alpha
argument cannot be used because it requires a scalar), but then the colorbar does not have access to values
and will just output a generic [0, 1]
bar:
normalize_max = lambda arr: arr / arr.max()
to_zero_one = lambda arr: normalize_max(arr - arr.min())
cmap = cm.get_cmap('hsv')
C = np.zeros((len(x), 4))
C[:, 3] = alpha
C[:, :3] = cmap(to_zero_one(value))[:, :3]
ax.set(title='plot with correct alpha')
scatter = ax.scatter(x, y, c=C)
fig.colorbar(scatter)
How can I have both the correct colorbar and alpha?