Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

python - Individual alpha values in scatter plot

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()

All my points_x, points_y and alpha_point have n values. However, I can't assign an array to the alpha parameter in scatter(). How can I have a different alpha value for each point? I can loop and plot point by point with each specific alpha value, but this doesn't seem like a good approach.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

New solution with matplotlib >= 3.4

Since matplotlib 3.4, alpha supports an iterable of multiple values: https://matplotlib.org/stable/users/whats_new.html#transparency-alpha-can-be-set-as-an-array-in-collections

import numpy as np
import matplotlib.pylab as plt

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

alphas = np.linspace(0.1, 1, 10)

plt.scatter(x, y, alpha=alphas)
plt.show()

Old solution for matplotlib < 3.4

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...