1

There are two similar questions about this:

  1. Individual alpha values in scatter plot
  2. Add alpha to an existing matplotlib colormap

but neither of these address this issue. I need to produce a scatter plot with individual alphas (as in question 1.) but I need to combine this with a given colormap (as in question 2.)

This is what I came up with:

import numpy as np
import matplotlib.pylab as plt
from matplotlib.colors import ListedColormap

x = np.arange(10)
y = np.arange(10)
# These are the colors for my data
z = np.arange(10)
# These are the alpha values for my data
alphas = np.linspace(0.1, 1, 10)

# Color map I want to use
cm = plt.cm.get_cmap('viridis')
# Get the colormap colors for my data
my_cmap = cm(z)
# Set alpha
my_cmap[:, -1] = alphas
# Create new colormap
my_cmap = ListedColormap(my_cmap)

plt.subplot(121)
plt.scatter(x, y, cmap=cm, c=z)
plt.subplot(122)
plt.scatter(x, y, cmap=my_cmap, c=z)
plt.show()

but the result is not what I expect:

enter image description here

where the image to the left is what the scatter plot looks like using the colormap and no alphas, and the plot to the right is my attempt to add individual alphas to the data points.

Gabriel
  • 40,504
  • 73
  • 230
  • 404

1 Answers1

2

Usual colormaps have 256 colors. Here you select only the first 10, which look roughly the same (all dark violet).

I suppose your code will run as expected when replacing my_cmap = cm(z) by

my_cmap = cm(plt.Normalize(z.min(), z.max())(z))

or

my_cmap = cm(np.linspace(0,1,len(z)))
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • I did try normalizing before posting the question, I used: `z_norm = (z - z.min()) / (z.max() - z.min())`, but it didn't work. Now I realize that it didn't work because I was running this with Python 2.7 where `z_norm = [0 0 0 0 0 0 0 0 0 1]` when obtained as shown above. In Python 3.7 the same line gives `z_norm = [0. 0.111 0.222 0.333 0.444 0.555 0.666 0.777 0.888 1.]` which works as expected. Thank you! – Gabriel Dec 03 '18 at 12:40
  • 1
    Both suggested lines here give the same result in py2 and py3. – ImportanceOfBeingErnest Dec 03 '18 at 12:44