pceccon pceccon - 6 months ago 27
Python Question

Individual alpha values in scatter plot / Matplotlib

I'm wondering if it is possible to have individual alpha values for each point to be plotted using the scatter function of Matplotlib. I need to plot a set of points, each one with its alpha value.

For example, I have this code to plot some points

def plot_singularities(points_x, p, alpha_point, file_path):
plt.figure()
plt.scatter(points_x, points_y, alpha=alpha_point)
plt.savefig(file_path + '.png', dpi=100)
plt.close()


Here, I all my points_x, points_y and alpha_point have n values. However, I can't assign an array to the alpha parameter in scater(). I'm wondering how can I have a different alpha value for each point.

I know that I can made a loop and plot point by point with its specific alpha value, but this not seems a good approach.

Thank you.

Answer

tcaswell's suggestion is correct, you can do it like this:

import numpy as np
import matplotlib.pylab as plt

x = np.arange(10)
y = np.arange(10)

alphas = np.linspace(0.1, 1, 10)
rgba_colors = np.zeros((10,4))
# for red the first column needs to be one
rgba_colors[:,0] = 1.0
# the fourth column needs to be your alphas
rgba_colors[:, 3] = alphas

plt.scatter(x, y, color=rgba_colors)
plt.show()

Output

Comments