2

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)

plot with correct colorbar plot with correct alpha

How can I have both the correct colorbar and alpha?

Exp HP
  • 695
  • 6
  • 24
  • @ImportanceOfBeingErnest can you please reconsider in light of the explanation I added for why this is not a duplicate? I did see that question earlier, and specifically constructed my MRE to ensure that that solution could not be applied. – Exp HP Jul 25 '19 at 23:12
  • 1
    I see, so you want a colorbar which does not actually show the colors of the scatter. That would be shown in [Matplotlib: Add colorbar to non-mappable object](https://stackoverflow.com/questions/43805821/matplotlib-add-colorbar-to-non-mappable-object) – ImportanceOfBeingErnest Jul 25 '19 at 23:33
  • Okay, thank you. Yes, that was helpful. – Exp HP Jul 25 '19 at 23:43
  • Can you post your solution as an answer? Thanks! – tommy.carstensen May 25 '20 at 02:27
  • @tommy.carstensen I cannot, since this is a duplicate. I believe it is fairly straightforward to apply the solution given in the (second) linked answer to this example, but here is a full solution if you are stuck: https://gist.github.com/ExpHP/0b02849899d0e55058ce5c6d4d532812 – Exp HP May 27 '20 at 04:18

0 Answers0