如何在Julia绘图中交互式绘制多边形以筛选点?
用Makie实现交互式多边形选点
我们可以借助Makie的交互事件系统,实现鼠标点击绘制多边形的功能,再结合你现有的PolygonOps筛选逻辑完成选点。以下是完整实现方案:
步骤1:初始化数据与交互状态
先准备示例点数据(替换成你的coord数据即可),并定义存储多边形顶点、绘制状态的变量:
using GLMakie, PolygonOps, StaticArrays # 模拟你的coord数据(替换为实际数据) coord = rand(100, 3) points = vec(SVector.(coord[:, 2], coord[:, 3])) # 交互状态变量 polygon_vertices = Point2f[] # 存储多边形顶点 is_drawing = false # 标记是否处于绘制状态 selected_points = Point2f[] # 存储选中的点
步骤2:构建绘图与交互回调
创建绘图窗口,添加鼠标点击、移动的回调函数,实现多边形的绘制与选点逻辑:
# 绘制原始点集 fig, ax, scatter_plot = scatter(points, color=:blue, markersize=8) # 初始化多边形预览 poly!(ax, polygon_vertices, color=(:lightblue, 0.3), strokecolor=:black, strokewidth=2) # 鼠标左键点击事件:添加顶点或结束绘制 on(events(fig).mousebutton) do event if event.button == Mouse.left && event.action == Mouse.press pos = mouseposition(ax) if !is_drawing # 第一次点击:开始绘制,清空历史顶点 empty!(polygon_vertices) push!(polygon_vertices, pos) is_drawing = true else # 判断是否点击起点附近,结束绘制 if norm(pos - first(polygon_vertices)) < 10 is_drawing = false # 调用你的多边形筛选函数 polygon = SVector.(polygon_vertices) inside = [inpolygon(p, polygon; in=true, on=false, out=false) for p in points] selected_points = points[inside] # 更新选中点的颜色 scatter_plot.color = [in ? :red : :blue for in in inside] else # 添加新的多边形顶点 push!(polygon_vertices, pos) end end # 更新多边形绘制 poly!(ax, polygon_vertices, color=(:lightblue, 0.3), strokecolor=:black, strokewidth=2, reset=true) end end # 鼠标移动事件:实时预览多边形(可选功能) on(events(fig).mouseposition) do _ if is_drawing && length(polygon_vertices) > 0 current_pos = mouseposition(ax) temp_vertices = vcat(polygon_vertices, current_pos) poly!(ax, temp_vertices, color=(:lightblue, 0.3), strokecolor=:black, strokewidth=2, reset=true) end end display(fig)
核心逻辑说明
- 绘制流程:左键第一次点击启动绘制,后续点击添加多边形顶点,再次点击起点附近(距离小于10像素)时结束绘制
- 顶点提取:结束绘制后,
polygon_vertices就是你需要的顶点集合,可通过xv = getindex.(polygon_vertices, 1)、yv = getindex.(polygon_vertices, 2)提取出对应的xv和yv向量 - 选点集成:自动调用你原有的
inpolygon筛选逻辑,选中的点会自动变为红色,方便直观查看
内容的提问来源于stack exchange,提问作者Gian Maria
相关产品推荐
相关产品推荐

