简介
在本实验中,你将学习如何使用 Python Matplotlib 通过套索工具交互式选择数据点。你将绘制一个散点图,然后通过在图表上围绕点绘制套索环来选择几个点。要进行绘制,只需在图表上点击、按住并拖动到你需要选择的点周围即可。
虚拟机提示
虚拟机启动完成后,点击左上角切换到“笔记本”标签以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,请随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。
导入库
导入必要的库,包括 numpy、Path 和 LassoSelector。
import numpy as np
from matplotlib.path import Path
from matplotlib.widgets import LassoSelector
创建选择器类
创建 SelectFromCollection 类,该类将使用 LassoSelector 从 Matplotlib 集合中选择索引。
class SelectFromCollection:
"""
使用 `LassoSelector` 从 matplotlib 集合中选择索引。
所选索引保存在 `ind` 属性中。此工具会淡化不属于所选内容的点(即降低它们的透明度值)。如果你的集合的透明度小于 1,此工具将永久更改透明度值。
请注意,此工具根据集合对象的 *原点*(即 `offsets`)来选择它们。
参数
----------
ax : `~matplotlib.axes.Axes`
要交互的轴。
collection : `matplotlib.collections.Collection` 的子类
你要从中选择的集合。
alpha_other : 0 <= 浮点数 <= 1
为了突出显示所选内容,此工具将所有选定的点设置为透明度值 1,未选定的点设置为 *alpha_other*。
"""
def __init__(self, ax, collection, 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.fc = collection.get_facecolors()
if len(self.fc) == 0:
raise ValueError('集合必须有一个面颜色')
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(19680801)
data = np.random.rand(100, 2)
subplot_kw = dict(xlim=(0, 1), ylim=(0, 1), autoscale_on=False)
fig, ax = plt.subplots(subplot_kw=subplot_kw)
pts = ax.scatter(data[:, 0], data[:, 1], s=80)
selector = SelectFromCollection(ax, pts)
接受所选点
使用回车键接受所选点,并将它们打印到控制台。
def accept(event):
if event.key == "enter":
print("Selected points:")
print(selector.xys[selector.ind])
selector.disconnect()
ax.set_title("")
fig.canvas.draw()
fig.canvas.mpl_connect("key_press_event", accept)
ax.set_title("Press enter to accept selected points.")
plt.show()
总结
在本实验中,你学习了如何使用 Python 的 Matplotlib 通过套索工具交互式地选择数据点。你创建了一个散点图,通过在图表上围绕点绘制套索环来选择一些点,然后使用回车键接受所选的点。