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

时间:2019-12-02 10:06:15

标签: python-3.x user-interface matplotlib scatter-plot

我想创建一个交互式散点图,以便用户可以使用光标选择点,因此选中的点将突出显示,其余的将被淡化。 现在,只有更改颜色后才能使用,如何更改不透明度并保留原始颜色?

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

1 个答案:

答案 0 :(得分:0)

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

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

欢呼