如何在ECharts水平树图中添加贯穿左右的分割线
如何在ECharts水平树图中添加贯穿左右边缘的分割线
需要在ECharts水平树图中添加一条贯穿左右边缘的分割线,效果参考下图:

现有如下HTML和JavaScript代码可生成无分割线的树图,需修改以添加类似树图曲线样式的分割线:
现有代码
HTML文件(tree.html)
<!DOCTYPE html> <html> <head> <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script> </head> <body> <div id="tree" style="width: 800px; height: 400px;"></div> <script src="tree.js"></script> </body> </html>
JavaScript文件(tree.js)
// 创建ECharts实例 var myChart = echarts.init(document.getElementById('tree')); var dogData = { name: 'Dog A', children: [ { name: 'Sire', children: [ { name: 'Sire Sire', }, { name: 'Sire Dam', }, ], }, { name: 'Dam', children: [ { name: 'Dam Sire', }, { name: 'Dam Dam', }, ], }, ], }; // 配置树图参数 var treeOption = { series: [ { type: 'tree', roam: true, layout: 'horizontal', data: [dogData], symbol: 'emptyCircle', symbolSize: 7, initialTreeDepth: -1, animationDurationUpdate: 750, label: { position: 'right', verticalAlign: 'middle', align: 'left', fontSize: 9 }, leaves: { label: { position: 'left', verticalAlign: 'middle', align: 'right' } }, }, ], }; // 渲染图表 myChart.setOption(treeOption);
解决方案:添加分割线
可以利用ECharts的graphic组件绘制自定义线条,匹配树图的曲线风格。修改后的tree.js代码如下:
// 创建ECharts实例 var myChart = echarts.init(document.getElementById('tree')); var dogData = { name: 'Dog A', children: [ { name: 'Sire', children: [ { name: 'Sire Sire', }, { name: 'Sire Dam', }, ], }, { name: 'Dam', children: [ { name: 'Dam Sire', }, { name: 'Dam Dam', }, ], }, ], }; // 配置树图参数 var treeOption = { // 添加graphic组件绘制分割线 graphic: [ { type: 'line', // 设置线条贯穿整个图表宽度,居中显示 shape: { x1: 0, y1: '50%', x2: '100%', y2: '50%' }, // 匹配树图虚线风格 style: { stroke: '#ccc', lineWidth: 1, lineDash: [5, 5] }, // 确保线条在树图下方,不遮挡节点和连线 z: 0 } ], series: [ { type: 'tree', roam: true, layout: 'horizontal', data: [dogData], symbol: 'emptyCircle', symbolSize: 7, initialTreeDepth: -1, animationDurationUpdate: 750, label: { position: 'right', verticalAlign: 'middle', align: 'left', fontSize: 9 }, leaves: { label: { position: 'left', verticalAlign: 'middle', align: 'right' } }, // 树图层级高于分割线 z: 1 }, ], }; // 渲染图表 myChart.setOption(treeOption);
关键说明
- 通过
graphic.line组件绘制水平线条,x1设为0、x2设为100%实现贯穿左右;y1和y2设为50%让线条居中。 - 用
lineDash配置虚线效果,颜色设为#ccc匹配示例图风格。 - 调整
z值确保分割线在树图下方(z:0),树图节点和连线在上方(z:1),避免遮挡。
内容的提问来源于stack exchange,提问作者J.W
相关产品推荐
相关产品推荐

