Python 散点图中的单个 alpha 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24767355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:09:44  来源:igfitidea点击:

Individual alpha values in scatter plot

pythonmatplotlibalphascatter-plot

提问by pceccon

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

我想知道是否可以使用scatterMatplotlib的函数为要绘制的每个点绘制单独的 alpha 值。我需要绘制一组点,每个点都有它的 alpha 值。

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_yand alpha_pointhave n values. However, I can't assign an array to the alphaparameter 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.

所有 my points_x,points_y并且alpha_point有 n 个值。然而,我不能分配一个阵列到alpha在参数scatter()。如何为每个点设置不同的 alpha 值?我可以使用每个特定的 alpha 值逐点循环和绘制,但这似乎不是一个好方法。

采纳答案by MaxNoe

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

tcaswell 的建议是正确的,你可以这样做:

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

输出

回答by Markus Dutschke

enter image description here

在此处输入图片说明

You can use the color argument and a colormap with alpha. cmaplinearly increases the alpha value from 0 to 1.

您可以使用颜色参数和带有 alpha 的颜色图。 cmap将 alpha 值从 0 线性增加到 1。

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

c='C0'

xs = np.arange(10)

fig, ax = plt.subplots(1, 1)
cmap = colors.LinearSegmentedColormap.from_list(
        'incr_alpha', [(0, (*colors.to_rgb(c),0)), (1, c)])
ax.scatter(xs, xs, c=xs, cmap=cmap, ec=None, s=10**2)

plt.show()