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

Python散点图按LOF值着色:解决重叠点显示优先级问题

解决重叠散点中高LOF值点被覆盖的问题

这个场景太常见了!当多个点坐标完全重合时,Matplotlib会按数据传入的顺序绘制,后画的点会盖在先画的上面——你现在的问题就是高LOF值的点先被画了,然后被低LOF的点盖住了,反过来调整顺序就行。

核心解决方案:按LOF值升序排序后绘图

我们只需要把数据按LOF值从小到大排序,让低LOF的点先绘制,高LOF的点最后绘制,就能保证高LOF的点显示在最上层。具体代码修改如下:

import pandas as pd
import matplotlib.pyplot as plt

# 原始数据
df = pd.DataFrame({'x': [1, 1], 'y': [1, 1]})
lof = pd.DataFrame({'lof': [2, 1]})

# 第一步:合并坐标数据和LOF值,方便统一排序
combined_data = pd.concat([df, lof], axis=1)
# 第二步:按LOF值升序排序(小的在前,大的在后)
sorted_data = combined_data.sort_values(by='lof')

# 第三步:用排序后的数据集绘图
fig = plt.figure(figsize=(4, 3), dpi=200)
plt.scatter(sorted_data['x'], sorted_data['y'], s=8, c=sorted_data['lof'])
plt.show()

进阶优化:差异化突出高LOF点

如果重叠点特别多,除了调整绘制顺序,还可以给高LOF的点单独设置更大的尺寸、特殊的标记样式,让它们更显眼:

# 拆分低LOF和高LOF数据集
low_lof_points = sorted_data[sorted_data['lof'] <= 1]
high_lof_points = sorted_data[sorted_data['lof'] > 1]

fig = plt.figure(figsize=(4, 3), dpi=200)
# 先画低LOF的点
plt.scatter(low_lof_points['x'], low_lof_points['y'], s=8, c=low_lof_points['lof'])
# 再画高LOF的点,用更大的尺寸和星形标记
plt.scatter(high_lof_points['x'], high_lof_points['y'], s=15, c=high_lof_points['lof'], marker='*')
plt.colorbar(label='LOF Value')
plt.show()

这样处理后,高LOF的离群点不仅不会被覆盖,还能通过视觉差异快速被识别出来~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:15:26