如何更改所选散点图点的不透明度

How to change the opacity of chosen scatter plot points

我想创建一个交互式散点图,以便用户可以 select 使用光标点,这样所选的点会突出显示,其余的会淡化。 现在它只有在颜色改变时才有效,我怎样才能改变不透明度并保持原来的颜色?

import numpy as np
from numpy.random import rand
from matplotlib.widgets import LassoSelector
from matplotlib.path import Path
import matplotlib.pyplot as plt


class SelectFromCollection(object):
    def __init__(self, ax, collection,c, alpha_other=0.3):
    self.canvas = ax.figure.canvas
    self.collection = collection
    self.alpha_other = alpha_other

    self.xys = collection.get_offsets()
    self.Npts = len(self.xys)
    self.c = c

    # Ensure that we have separate colors for each object
    self.fc = collection.get_facecolors()
    if len(self.fc) == 0:
        raise ValueError('Collection must have a facecolor')
    elif len(self.fc) == 1:
        self.fc = np.tile(self.fc, (self.Npts, 1))
    self.lasso = LassoSelector(ax, onselect=self.onselect)
    self.ind = []

def onselect(self, verts):
    path = Path(verts)
    self.ind = np.nonzero(path.contains_points(self.xys))[0]
    self.fc[:, -1] = self.alpha_other
    self.fc[self.ind, -1] = 1
    self.collection.set_facecolors(self.fc)
    self.canvas.draw_idle()

def disconnect(self):
    self.lasso.disconnect_events()
    self.fc[:, -1] = 1
    self.collection.set_facecolors(self.fc)
    self.canvas.draw_idle()


np.random.seed(1)
x, y, c = rand(3, 100)
subplot_kw = dict(xlim=(0, 1), ylim=(0, 1), autoscale_on=False)
fig, ax = plt.subplots(subplot_kw=subplot_kw)
pts = ax.scatter(x, y,c=c, s=100)
selector = SelectFromCollection(ax, pts, c)
plt.show()

已解决,我使用方法 self.collection.get_facecolors() 来获取格式和值,然后我只是更改了所选索引的第 3 列的值,如下所示:

fc = self.collection.get_facecolors()
fc[self.ind, 3] = 1
fc[others, 3] = self.alpha_other
self.collection.set_facecolors(fc)

干杯