散点图中的单个 alpha 值 [英] Individual alpha values in scatter plot

查看:46
本文介绍了散点图中的单个 alpha 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

例如,我有这个代码来绘制一些点

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

我所有的 points_xpoints_yalpha_point 都有 n 个值.但是,我无法将数组分配给 scatter() 中的 alpha 参数.如何为每个点设置不同的 alpha 值?我可以使用每个特定的 alpha 值逐点循环和绘制,但这似乎不是一个好方法.

解决方案

使用 matplotlib >= 3.4 的新解决方案

从 matplotlib 3.4 开始,alpha 支持多个值的迭代:

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.

解决方案

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

这篇关于散点图中的单个 alpha 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆