You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询CairoMakie散点图标签非重叠自动放置算法

解决CairoMakie散点图标签重叠问题

CairoMakie原生支持说明

目前CairoMakie没有内置的自动标签避重叠布局算法,手动调整offset确实没法适配所有数据集。

方案1:用Julia第三方包LabelFit自动处理

LabelFit是Julia生态里专门做标签放置的工具,支持自动规避重叠,能直接和Makie配合使用。

安装及使用示例

先安装包:

using Pkg
Pkg.add("LabelFit")

修改你的代码如下:

using CairoMakie
using LabelFit

x = [0, 0.5, 0.50]
y = [0, 0.5, 0.51]
lbls = ["O", "A", "B"]

fig = Figure()
ax = Axis(fig[1,1])
scatter!(ax, x, y, marker=:circle, markersize=10, color=:red)

# 调用fit_labels计算不重叠的标签位置
positions = fit_labels(Point2f.(x, y), lbls; fontsize=12)
foreach(i -> text!(ax, positions[i], lbls[i], fontsize=12), 1:3)

display(fig)

fit_labels会自动计算每个标签的最优位置,避开其他标签和散点,还能通过参数调整字体大小、边距等细节。

方案2:手动实现简单避重叠逻辑(适合小规模数据)

如果不想加新包,可以自己写个简单的距离检测逻辑,给近距离的标签加偏移:

using CairoMakie

x = [0, 0.5, 0.50]
y = [0, 0.5, 0.51]
lbls = ["O", "A", "B"]
points = Point2f.(x, y)

fig = Figure()
ax = Axis(fig[1,1])
scatter!(ax, x, y, marker=:circle, markersize=10, color=:red)

# 定义偏移步长和距离阈值
offset_step = 0.02
distance_threshold = 0.015
offsets = zeros(Point2f, length(points))

# 遍历点对,给近距离的点添加反向偏移
for i in 1:length(points)
    for j in i+1:length(points)
        if norm(points[i] - points[j]) < distance_threshold
            offsets[i] += Point2f(offset_step, 0)
            offsets[j] += Point2f(-offset_step, 0)
        end
    end
end

# 绘制带偏移的标签
foreach(i -> text!(ax, points[i] + offsets[i], lbls[i]), 1:3)

display(fig)

这个逻辑会检测距离过近的点对,给它们加水平反向偏移,你可以根据需求调整偏移方向、步长和阈值。

内容的提问来源于stack exchange,提问作者cbsteh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 14:10:28