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

如何为不同类别散点周边填充同类颜色生成无点分区可视化图

你要实现的这个效果本质是沃罗诺伊图(Voronoi Diagram,也叫泰森多边形),它会根据给定点的位置,将平面划分为多个区域,每个区域内的所有点到对应散点的距离都小于到其他散点的距离,刚好可以对应你需要的「散点周边区域填充同类颜色」的需求。

Python 实现方法

你可以配合scipy的Voronoi模块和matplotlib实现,示例代码如下:

import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Voronoi, voronoi_plot_2d

# 模拟你的散点数据:假设有3类,共100个点
n_points = 100
n_classes = 3
points = np.random.rand(n_points, 2)  # 散点坐标
labels = np.random.randint(0, n_classes, n_points)  # 每个点的类别
# 自定义每类对应的颜色,和你原来的散点颜色对应即可
class_colors = ['#ff7f0e', '#2ca02c', '#1f77b4']

# 生成沃罗诺伊图
vor = Voronoi(points)

# 绘图
fig, ax = plt.subplots()
# 遍历每个区域,填充对应颜色
for point_idx, region_idx in enumerate(vor.point_region):
    region = vor.regions[region_idx]
    if -1 not in region:  # 排除边界外的无限区域
        polygon = [vor.vertices[i] for i in region]
        ax.fill(*zip(*polygon), color=class_colors[labels[point_idx]], alpha=0.8)

# 可选:隐藏坐标轴、去掉边框,和你示例效果对齐
ax.set_xlim(points[:,0].min(), points[:,0].max())
ax.set_ylim(points[:,1].min(), points[:,1].max())
ax.axis('off')
plt.show()

如果需要处理边界外的无限区域,可以额外做坐标裁剪,或者用voronoi_plot_2d的参数直接调整显示范围即可。

R 实现方法

用ggvoronoi包配合ggplot2实现更简单:

library(ggplot2)
library(ggvoronoi)

# 模拟散点数据
n_points <- 100
df <- data.frame(
  x = runif(n_points),
  y = runif(n_points),
  class = sample(c("A","B","C"), n_points, replace = T)
)

ggplot(df, aes(x = x, y = y)) +
  geom_voronoi(aes(fill = class), alpha = 0.8) +
  # 限制和原始散点相同的显示范围,去掉多余边界
  lims(x = c(0,1), y = c(0,1)) +
  theme_void()

如果要和你原来的散点颜色完全对齐,只需要把填充色的映射规则改成和你之前散点的配色规则一致即可,不需要绘制原始散点就能直接生成填充效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 17:27:04