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

如何为Matplotlib中编号的多边形指定自定义颜色(含HSLUV实现)

多边形交集区域的自定义颜色设置方案

多边形交集图

原实现逻辑

先创建Point点,将其缓冲为圆形多边形,再将圆形边界线合并后多边形化,得到所有相交区域的多边形,手动标注了各多边形的质心编号。

需求

  1. 精准指定每个编号多边形的颜色(例如编号0、9、13、17、2设为蓝色,编号11设为黄色)
  2. 可选结合HSLUV库实现颜色设置

解决方案

一、精准指定自定义颜色

核心思路是建立多边形与编号的映射关系,通过质心距离匹配自动关联,再根据编号分配指定颜色:

  1. 定义颜色映射字典,明确每个编号对应的颜色
  2. 遍历生成的多边形,计算其质心与手动标注的质心点的距离,匹配对应的编号
  3. 根据编号从颜色字典中取色,无指定颜色的多边形用默认色填充

修改后的完整代码:

import matplotlib.pyplot as plt
from shapely.geometry import Point, LineString
from shapely.ops import unary_union, polygonize
import numpy as np

def plot_coords(coords, color):
    pts = list(coords)
    x, y = zip(*pts)
    plt.plot(x, y, color=color)
    plt.fill_between(x, y, facecolor=color, alpha=0.7)  # 加alpha提升视觉效果

points = [Point(6, 0),
          Point(5, 1.72),
          Point(3, 1.73),
          Point(2, 0),
          Point(3, -1.73),
          Point(5, -1.73)]

# 创建圆形多边形
circles = [point.buffer(2) for point in points]

# 合并边界线并多边形化得到交集区域
rings = [LineString(list(pol.exterior.coords)) for pol in circles]
union = unary_union(rings)
result = [geom for geom in polygonize(union)]

# 手动标注的质心点与编号对应
centroid_coords = [
    Point(7.210123936676805, -0.0014481952154823),    # 0
    Point(5.817327756517152, -1.0513260084561042),    # 1
    Point(5.603133733696165, -2.7765635631249412),    # 2
    Point(4.500525247710033, -0.8659667639805515),    # 3
    Point(3.9999999999880367, -2.089987631283091),    # 4
    Point(5.001117020126147, -0.0049682528095108),    # 7
    Point(5.815010886603158, 1.044998514899447),      # 9
    Point(4.500000000000001, 0.8649999999999999),     # 11
    Point(4.001448625652675, 2.087475424328895),      # 12
    Point(5.60401724850886, 2.7710509908378467),      # 13
    Point(3.4999775973742575, -0.8650387450203051),   # 15
    Point(2.1869624905370935, -1.0465658077069044),   # 17
    Point(2.9989568960908466, -0.0000271066971084),   # 19
    Point(3.499481641504979, 0.8609597712896809),     # 20
    Point(2.183590487640668, 1.0478993334094695),     # 21
    Point(2.400064213432032, 2.777072141054654),      # 22
    Point(0.7919163421701616, 0.0000000000000001),    # 24
    Point(2.396866266303837, -2.776563563124941)      # 26
]
# 编号与质心的映射
id_to_centroid = {i: pt for i, pt in enumerate(centroid_coords)}

# 定义颜色映射:键是编号,值是颜色(支持Matplotlib颜色名称、RGB、十六进制)
color_map = {
    0: 'blue',
    2: 'blue',
    9: 'blue',
    13: 'blue',
    17: 'blue',
    11: 'yellow',
    # 可继续添加其他编号的颜色指定
}
default_color = '#cccccc'  # 默认灰色

fig = plt.figure()
ax = fig.add_subplot()
fig.subplots_adjust(top=0.85)

# 遍历每个多边形,匹配编号并设置颜色
for poly in result:
    poly_centroid = poly.centroid
    # 找到距离最近的手动标注质心,匹配编号
    distances = [(abs(poly_centroid.distance(pt)), idx) for idx, pt in id_to_centroid.items()]
    min_dist, matched_id = min(distances)
    # 获取对应颜色
    color = color_map.get(matched_id, default_color)
    # 绘制多边形
    plot_coords(poly.exterior.coords, color)

# 绘制质心编号
for idx, pt in id_to_centroid.items():
    plt.scatter(pt.x, pt.y, marker=f"${idx}$", color='black', zorder=10)

ax.set_aspect('equal')
plt.show()

二、结合HSLUV库实现颜色设置

HSLUV是感知均匀的颜色空间,适合生成协调的配色。使用步骤:

  1. 安装依赖:pip install hsluv
  2. 使用hsluv.hsluv_to_rgb()将HSLUV颜色值转换为Matplotlib支持的RGB元组

修改颜色映射部分的代码示例:

import hsluv

# 用HSLUV定义颜色
color_map = {
    0: hsluv.hsluv_to_rgb((240, 100, 50)),   # 蓝色
    2: hsluv.hsluv_to_rgb((240, 100, 50)),
    9: hsluv.hsluv_to_rgb((240, 100, 50)),
    13: hsluv.hsluv_to_rgb((240, 100, 50)),
    17: hsluv.hsluv_to_rgb((240, 100, 50)),
    11: hsluv.hsluv_to_rgb((60, 100, 70)),    # 黄色
    # 更多HSLUV颜色:(色相, 饱和度, 明度),范围分别是0-360, 0-100, 0-100
}

将这段代码替换原方案中的color_map定义即可,其余逻辑保持不变。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 04:48:16