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

基于Django后端如何在前端绘制SciPy生成的聚类树状图dendrogram

SciPy树状图输出转前端层级格式的实现方案

后端(Django侧)数据转换

无需使用scipy.cluster.hierarchy.dendrogram输出的折线坐标结构转换,直接通过生成树状图前的linkage矩阵即可快速生成前端需要的父子层级结构,逻辑更简单、转换效率更高。

linkage矩阵每行结构为[聚类1id, 聚类2id, 两个聚类的距离, 聚类包含的样本总数],初始id范围0~n-1对应原始样本,id≥n的为合并后生成的新聚类,转换代码如下:

import scipy.cluster.hierarchy as sch

def linkage_to_hierarchy(linkage_mat, sample_names: list):
    sample_count = len(sample_names)
    # 初始化节点字典,初始为所有原始样本节点
    node_map = {
        idx: {"name": sample_names[idx], "children": []} 
        for idx in range(sample_count)
    }
    new_cluster_id = sample_count
    for row in linkage_mat:
        c1_id, c2_id, distance, _ = row
        c1_id, c2_id = int(c1_id), int(c2_id)
        # 生成合并后的新聚类节点
        new_node = {
            "name": f"cluster_{new_cluster_id}",
            "distance": float(distance),
            "children": [node_map[c1_id], node_map[c2_id]]
        }
        node_map[new_cluster_id] = new_node
        new_cluster_id += 1
    # 最后生成的节点就是树的根节点,直接返回给前端即可
    return node_map[new_cluster_id - 1]

转换后的结构可直接作为接口返回值传给前端,字段可根据业务需求自行扩展,比如添加聚类包含的样本列表、聚类特征等。

前端(Angular侧)渲染

目前主流的前端可视化库都原生支持上述父子层级结构,无需额外转换:

  • 若使用ECharts/ngx-echarts,直接将返回的根节点放入tree系列的data字段即可,可通过distance字段控制连线长度、添加边标签显示距离值,示例配置:
import { Component } from '@angular/core';
import { EChartsOption } from 'echarts';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-dendrogram',
  template: `<echarts [options]="chartOption" style="width: 100%; height: 600px;"></echarts>`
})
export class DendrogramComponent {
  chartOption: EChartsOption = {
    tooltip: { trigger: 'item' },
    series: [{
      type: 'tree',
      orient: 'LR',
      label: { position: 'right' },
      edgeLabel: { 
        show: true, 
        formatter: (params) => params.data.distance?.toFixed(2) 
      },
      leaves: { label: { position: 'right' } },
      expandAndCollapse: true, // 支持聚类折叠交互
      data: []
    }]
  };

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http.get('/api/get-dendrogram-data').subscribe((rootNode: any) => {
      // ECharts的tree系列data要求为数组,放入根节点即可
      this.chartOption.series[0].data = [rootNode];
    });
  }
}
  • 若使用D3.js,直接调用d3.hierarchy(后端返回的根节点)生成层级实例,再配合d3.cluster()布局即可完成自定义渲染。

优化注意事项

  • 样本量超过1000时建议在后端对低层级聚类进行合并裁剪,减少前端渲染压力
  • 若需要和Python侧生成的静态树状图样式完全对齐,可直接将dendrogram返回的icoord(x坐标)、dcoord(y坐标)字段传给前端,直接通过SVG/Canvas绘制折线即可,该方式无层级结构,不支持交互
  • 可根据业务需求给节点添加自定义字段,比如聚类的轮廓系数、特征重要性等,用于前端tooltip展示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:51:02