【AntV-G6】决策树简单实例

2023-12-14 13:59
文章标签 简单 实例 决策树 antv g6

本文主要是介绍【AntV-G6】决策树简单实例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

使用步骤

  1. 复制treeMind.vue文件到前端页面目录,
  2. 在需要展示的页面引入treeMind
  3. npm install错误解决方法

树组件 treeMind.vue

<template><div id="container"></div>
</template><script>
import insertCss from "insert-css";
import G6 from "@antv/g6";export default {name: "treeMind",props: {// 数据data: {type: Object,default() {return {};}},//高height: {type: Number,default() {return 500;}}},data() {return {}},mounted() {},methods: {init(mockData) {insertCss(`.g6-component-tooltip {background-color: rgba(0,0,0, 0.65);padding: 10px;box-shadow: rgb(174, 174, 174) 0px 0px 10px;width: fit-content;color: #fff;border-radius = 4px;}`);const colors = {BLUE: '#5B8FF9',RED: '#F46649',YELLOW: '#EEBC20',GREEN: '#5BD8A6',DARKGREY: '#A7A7A7',BROWN: '#A98847',};//  组件propsconst props = {data: mockData ? mockData : this.data,config: {padding: [20, 50],defaultLevel: 3,defaultZoom: 0.8,modes: {default: ['zoom-canvas', 'drag-canvas']},},};const container = document.getElementById('container');const width = container.scrollWidth;const height = container.scrollHeight || 600;// 默认配置const defaultConfig = {width,height,modes: {default: ['zoom-canvas', 'drag-canvas'],},fitView: true,animate: true,defaultNode: {type: 'flow-rect',},defaultEdge: {type: 'cubic-horizontal',style: {stroke: '#CED4D9',},},layout: {type: 'indented',direction: 'LR',dropCap: false,indent: 300,getHeight: () => {return 60;},},};// 自定义节点、边const registerFn = () => {/*** 自定义节点*/G6.registerNode('flow-rect',{shapeType: 'flow-rect',draw(cfg, group) {const {name = '',qty,collapsed,unit,color,rate} = cfg;const grey = '#CED4D9';const rectConfig = {width: 140,height: 50,lineWidth: 1,fontSize: 12,fill: '#fff',radius: 4,stroke: grey,opacity: 1,};const nodeOrigin = {x: -rectConfig.width / 2,y: -rectConfig.height / 2,};const textConfig = {//center / end / left / right / starttextAlign: 'center',//top / middle / bottom / alphabetic / hangingtextBaseline: 'bottom',};const rect = group.addShape('rect', {attrs: {x: nodeOrigin.x,y: nodeOrigin.y,...rectConfig,},});const rectBBox = rect.getBBox();// namegroup.addShape('text', {attrs: {...textConfig,x: 0 ,y: 20 + nodeOrigin.y,text: name.length > 28 ? name.substr(0, 28) + '...' : name,fontSize: 12,opacity: 0.85,fill: '#000',cursor: 'pointer',},name: 'name-shape',});// qtyconst qtyLabel = group.addShape('text', {attrs: {...textConfig,//调整数量的宽x: -4,y: rectBBox.maxY - 12,text: qty,fontSize: 12,fill: '#000',opacity: 0.85,},});//  unitgroup.addShape('text', {attrs: {...textConfig,//调整单位的宽x: qtyLabel.getBBox().maxX +20,y: rectBBox.maxY - 12,text: unit,fontSize: 12,fill: '#000',opacity: 0.75,},});// bottom line backgroundconst bottomBackRect = group.addShape('rect', {attrs: {x: nodeOrigin.x,y: rectBBox.maxY - 4,width: rectConfig.width,height: 4,radius: [0, 0, rectConfig.radius, rectConfig.radius],fill: '#E0DFE3',},});// bottom percentconst bottomRect = group.addShape('rect', {attrs: {x: nodeOrigin.x,y: rectBBox.maxY - 4,width: rate * rectBBox.width,height: 4,radius: [0, 0, rectConfig.radius, rectConfig.radius],fill: colors[color],},});// collapse rectif (cfg.children && cfg.children.length) {group.addShape('rect', {attrs: {x: rectConfig.width / 2 - 8,y: -8,width: 16,height: 16,stroke: 'rgba(0, 0, 0, 0.25)',cursor: 'pointer',fill: '#fff',},name: 'collapse-back',modelId: cfg.id,});// collpase textgroup.addShape('text', {attrs: {x: rectConfig.width / 2,y: 0,textAlign: 'center',textBaseline: 'middle',text: collapsed ? '+' : '-',fontSize: 16,cursor: 'pointer',fill: 'rgba(0, 0, 0, 0.25)',},name: 'collapse-text',modelId: cfg.id,});}this.drawLinkPoints(cfg, group);return rect;},update(cfg, item) {const {level, color, name} = cfg;const group = item.getContainer();let mask = group.find(ele => ele.get('name') === 'mask-shape');let maskLabel = group.find(ele => ele.get('name') === 'mask-qty-shape');if (level === 0) {group.get('children').forEach(child => {if (child.get('name')?.includes('collapse')) return;child.hide();})if (!mask) {mask = group.addShape('rect', {attrs: {x: -101,y: -30,width: 202,height: 60,opacity: 0,fill: colors[color]},name: 'mask-shape',});maskLabel = group.addShape('text', {attrs: {fill: '#fff',fontSize: 20,x: 0,y: 10,text: name.length > 28 ? name.substr(0, 16) + '...' : name,textAlign: 'center',opacity: 0,},name: 'mask-qty-shape',});const collapseRect = group.find(ele => ele.get('name') === 'collapse-back');const collapseText = group.find(ele => ele.get('name') === 'collapse-text');collapseRect?.toFront();collapseText?.toFront();} else {mask.show();maskLabel.show();}mask.animate({opacity: 1}, 200);maskLabel.animate({opacity: 1}, 200);return mask;} else {group.get('children').forEach(child => {if (child.get('name')?.includes('collapse')) return;child.show();})mask?.animate({opacity: 0}, {duration: 200,callback: () => mask.hide()});maskLabel?.animate({opacity: 0}, {duration: 200,callback: () => maskLabel.hide()});}this.updateLinkPoints(cfg, group);},setState(name, value, item) {if (name === 'collapse') {const group = item.getContainer();const collapseText = group.find((e) => e.get('name') === 'collapse-text');if (collapseText) {if (!value) {collapseText.attr({text: '-',});} else {collapseText.attr({text: '+',});}}}},getAnchorPoints() {return [[0, 0.5],[1, 0.5],];},},'rect',);G6.registerEdge('flow-cubic',{getControlPoints(cfg) {let controlPoints = cfg.controlPoints; // 指定controlPointsif (!controlPoints || !controlPoints.length) {const {startPoint, endPoint, sourceNode, targetNode} = cfg;const {x: startX, y: startY, coefficientX, coefficientY} = sourceNode? sourceNode.getModel(): startPoint;const {x: endX, y: endY} = targetNode ? targetNode.getModel() : endPoint;let curveStart = (endX - startX) * coefficientX;let curveEnd = (endY - startY) * coefficientY;curveStart = curveStart > 40 ? 40 : curveStart;curveEnd = curveEnd < -30 ? curveEnd : -30;controlPoints = [{x: startPoint.x + curveStart, y: startPoint.y},{x: endPoint.x + curveEnd, y: endPoint.y},];}return controlPoints;},getPath(points) {const path = [];path.push(['M', points[0].x, points[0].y]);path.push(['C',points[1].x,points[1].y,points[2].x,points[2].y,points[3].x,points[3].y,]);return path;},},'single-line',);};registerFn();const {data} = props;let graph = null;const initGraph = (data) => {if (!data) {return;}const {onInit, config} = props;const tooltip = new G6.Tooltip({// offsetX and offsetY include the padding of the parent containeroffsetX: 20,offsetY: 30,// the types of items that allow the tooltip show up// 允许出现 tooltip 的 item 类型itemTypes: ['node'],// custom the tooltip's content// 自定义 tooltip 内容getContent: (e) => {const outDiv = document.createElement('div');//outDiv.style.padding = '0px 0px 20px 0px';const nodeName = e.item.getModel().name;let formatedNodeName = '';for (let i = 0; i < nodeName.length; i++) {formatedNodeName = `${formatedNodeName}${nodeName[i]}`;if (i !== 0 && i % 20 === 0) formatedNodeName = `${formatedNodeName}<br/>`;}outDiv.innerHTML = `${formatedNodeName}`;return outDiv;},shouldBegin: (e) => {if (e.target.get('name') === 'name-shape' || e.target.get('name') === 'mask-qty-shape') return true;return false;},});graph = new G6.TreeGraph({container: 'container',...defaultConfig,...config,plugins: [tooltip],});if (typeof onInit === 'function') {onInit(graph);}graph.data(data);graph.render();const handleCollapse = (e) => {const target = e.target;const id = target.get('modelId');const item = graph.findById(id);const nodeModel = item.getModel();nodeModel.collapsed = !nodeModel.collapsed;graph.layout();graph.setItemState(item, 'collapse', nodeModel.collapsed);};graph.on('collapse-text:click', (e) => {handleCollapse(e);});graph.on('collapse-back:click', (e) => {handleCollapse(e);});// 监听画布缩放,缩小到一定程度,节点显示缩略样式let currentLevel = 1;const briefZoomThreshold = Math.max(graph.getZoom(), 0.5);graph.on('viewportchange', e => {if (e.action !== 'zoom') return;const currentZoom = graph.getZoom();let toLevel = currentLevel;if (currentZoom < briefZoomThreshold) {toLevel = 0;} else {toLevel = 1;}if (toLevel !== currentLevel) {currentLevel = toLevel;graph.getNodes().forEach(node => {graph.updateItem(node, {level: toLevel})})}});};initGraph(data);if (typeof window !== 'undefined')window.onresize = () => {if (!graph || graph.get('destroyed')) return;if (!container || !container.scrollWidth || !container.scrollHeight) return;graph.changeSize(container.scrollWidth, container.scrollHeight);};},}
}
</script><style scoped>
#container {width: 100%;height: 100%;
}
</style>

引入treeMind.vue (复制到页面)


<template><treeMind ref="treeMind"></treeMind>
</template><script>
export default {name: "tree",components: {TreeMind,},data() {return {//树的数据格式(可自定义字段,需更改treeMind.vue中的参数)treeData: {}};},methods: {// 获取后端传的树格式数据,如 treeDataqueryTreeData(data).then((res) => {if (res.status == 0) {// 初始化树组件,并传入树格式的数据res.data[0]this.$nextTick(() => {this.$refs.treeMind.init(res.data[0]);});} else {this.$message.error(res.msg);}});}
}
</script>

树的数据格式如下(可自定义字段)

treeData: {id: 'g1',name: 'Name1',qty: '538.90',unit: 'Yuan',rate: 1.0,color: 'BULE',children: [{id: 'g12',name: 'Deal with LONG qty',qty: '338.00',unit: 'Yuan',rate: 1,color: 'RED',children: [{id: 'g121',name: 'Name3',collapsed: true,qty: '138.00',rate: 1,color: 'BULE',unit: 'Yuan',children: [],},{id: 'g122',name: 'Name5',collapsed: true,qty: '100.00',rate: 1,color: 'GREEN',unit: 'Yuan',children: [],},],},{id: 'g13',name: 'Name9',qty: '100.90',rate: 1,color: 'BULE',unit: 'Yuan',children: [{id: 'g131',name: 'Name10',qty: '33.90',rate: 1,color: 'RED',unit: 'Yuan',children: [],},{id: 'g132',name: 'Name11',qty: '67.00',rate: 1,color: 'GREEN',unit: 'Yuan',children: [],},],},{id: 'g14',name: 'Name12',qty: '100.00',rate: 1,color: 'GREEN',unit: 'Yuan',children: [],},],}

npm install报错

在这里插入图片描述

typescript版本问题,图片上是3.9.10,在package.json文件里更改为"typescript": "^4.2.4",再重新npm install即可

这篇关于【AntV-G6】决策树简单实例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/492796

相关文章

基于Qt开发一个简单的OFD阅读器

《基于Qt开发一个简单的OFD阅读器》这篇文章主要为大家详细介绍了如何使用Qt框架开发一个功能强大且性能优异的OFD阅读器,文中的示例代码讲解详细,有需要的小伙伴可以参考一下... 目录摘要引言一、OFD文件格式解析二、文档结构解析三、页面渲染四、用户交互五、性能优化六、示例代码七、未来发展方向八、结论摘要

Oracle Expdp按条件导出指定表数据的方法实例

《OracleExpdp按条件导出指定表数据的方法实例》:本文主要介绍Oracle的expdp数据泵方式导出特定机构和时间范围的数据,并通过parfile文件进行条件限制和配置,文中通过代码介绍... 目录1.场景描述 2.方案分析3.实验验证 3.1 parfile文件3.2 expdp命令导出4.总结

MySQL的索引失效的原因实例及解决方案

《MySQL的索引失效的原因实例及解决方案》这篇文章主要讨论了MySQL索引失效的常见原因及其解决方案,它涵盖了数据类型不匹配、隐式转换、函数或表达式、范围查询、LIKE查询、OR条件、全表扫描、索引... 目录1. 数据类型不匹配2. 隐式转换3. 函数或表达式4. 范围查询之后的列5. like 查询6

MyBatis框架实现一个简单的数据查询操作

《MyBatis框架实现一个简单的数据查询操作》本文介绍了MyBatis框架下进行数据查询操作的详细步骤,括创建实体类、编写SQL标签、配置Mapper、开启驼峰命名映射以及执行SQL语句等,感兴趣的... 基于在前面几章我们已经学习了对MyBATis进行环境配置,并利用SqlSessionFactory核

Python开发围棋游戏的实例代码(实现全部功能)

《Python开发围棋游戏的实例代码(实现全部功能)》围棋是一种古老而复杂的策略棋类游戏,起源于中国,已有超过2500年的历史,本文介绍了如何用Python开发一个简单的围棋游戏,实例代码涵盖了游戏的... 目录1. 围棋游戏概述1.1 游戏规则1.2 游戏设计思路2. 环境准备3. 创建棋盘3.1 棋盘类

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

csu 1446 Problem J Modified LCS (扩展欧几里得算法的简单应用)

这是一道扩展欧几里得算法的简单应用题,这题是在湖南多校训练赛中队友ac的一道题,在比赛之后请教了队友,然后自己把它a掉 这也是自己独自做扩展欧几里得算法的题目 题意:把题意转变下就变成了:求d1*x - d2*y = f2 - f1的解,很明显用exgcd来解 下面介绍一下exgcd的一些知识点:求ax + by = c的解 一、首先求ax + by = gcd(a,b)的解 这个

hdu2289(简单二分)

虽说是简单二分,但是我还是wa死了  题意:已知圆台的体积,求高度 首先要知道圆台体积怎么求:设上下底的半径分别为r1,r2,高为h,V = PI*(r1*r1+r1*r2+r2*r2)*h/3 然后以h进行二分 代码如下: #include<iostream>#include<algorithm>#include<cstring>#include<stack>#includ

usaco 1.3 Prime Cryptarithm(简单哈希表暴搜剪枝)

思路: 1. 用一个 hash[ ] 数组存放输入的数字,令 hash[ tmp ]=1 。 2. 一个自定义函数 check( ) ,检查各位是否为输入的数字。 3. 暴搜。第一行数从 100到999,第二行数从 10到99。 4. 剪枝。 代码: /*ID: who jayLANG: C++TASK: crypt1*/#include<stdio.h>bool h

【机器学习】高斯过程的基本概念和应用领域以及在python中的实例

引言 高斯过程(Gaussian Process,简称GP)是一种概率模型,用于描述一组随机变量的联合概率分布,其中任何一个有限维度的子集都具有高斯分布 文章目录 引言一、高斯过程1.1 基本定义1.1.1 随机过程1.1.2 高斯分布 1.2 高斯过程的特性1.2.1 联合高斯性1.2.2 均值函数1.2.3 协方差函数(或核函数) 1.3 核函数1.4 高斯过程回归(Gauss