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

基于PyQGIS为矢量图层按CLASSE字段配置分类颜色符号

QGIS矢量图层分类颜色符号配置问题解决方案

环境

  • Windows 11
  • QGIS 3.16.14
  • Python 3.9

需求

为矢量图层zone_fuse_comune_min_corr_ok的CLASSE字段(属性值为S1、S2、S3)配置分类颜色符号,样式匹配指定目标图片。

现有问题

参考示例代码修改后存在两个问题:

  1. S1、S2、S3均使用同一颜色#bed2ff,无法按属性分配不同颜色;
  2. 图例中属性顺序为S1、S3、S2,不符合预期的S1、S2、S3顺序。

解决方案

修改后的代码

from qgis.core import (
    QgsProject,
    QgsCategorizedSymbolRenderer,
    QgsSymbol,
    QgsRendererCategory,
    QColor
)

# 获取目标图层
layer = QgsProject.instance().mapLayersByName('zone_fuse_comune_min_corr_ok')[0]

# 按预期顺序定义每个分类对应的颜色(可替换为目标样式的颜色值)
class_config = [
    ('S1', '#bed2ff'),
    ('S2', '#ffcc99'),
    ('S3', '#99eebb')
]

# 创建分类符号列表
categories = []
for class_val, color_hex in class_config:
    # 为每个分类创建独立符号
    symbol = QgsSymbol.defaultSymbol(layer.geometryType())
    symbol.setColor(QColor(color_hex))
    # 创建分类项
    category = QgsRendererCategory(class_val, symbol, class_val)
    categories.append(category)

# 初始化分类渲染器并应用
renderer = QgsCategorizedSymbolRenderer('CLASSE', categories)
if renderer.isValid():
    layer.setRenderer(renderer)
    layer.triggerRepaint()
    # 更新图例显示
    iface.layerTreeView().refreshLayerSymbology(layer.id())

关键修复点

  1. 颜色分配问题:不再复用单个符号实例,而是为每个分类单独创建QgsSymbol并设置对应颜色,确保每个属性值匹配独立颜色;
  2. 图例顺序问题:通过有序列表class_config严格定义S1、S2、S3的顺序,生成分类项时直接遵循该顺序,最终图例将按预期排列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:55:28