AmCharts 是一个功能强大的 JavaScript 图表库,用于创建各种类型的图表,包括柱状图、折线图、饼图等。强制定向树(Force-Directed Tree)是一种图表类型,用于展示层次结构数据,其中节点之间的连接基于力导向算法,使得图表布局更加自然。
AmCharts 中的强制定向树主要有以下几种类型:
要在 AmCharts 的强制定向树上仅展开第一级子对象,可以通过以下步骤实现:
以下是一个示例代码:
// 引入 AmCharts 库
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>
// 创建图表实例
var chart = am5xy.XYChart.new(am5.Root.new("chartdiv"), {
panX: false,
panY: false,
wheelX: "panX",
wheelY: "zoomX",
layout: root => {
var layout = am5 ForceDirectedTree.new(root, 1, 1);
layout.iterations = 2;
return layout;
}
});
// 加载数据
chart.data.setAll([
{
"name": "Root",
"children": [
{
"name": "Level 1 - A",
"children": [
{ "name": "Level 2 - A1" },
{ "name": "Level 2 - A2" }
]
},
{
"name": "Level 1 - B",
"children": [
{ "name": "Level 2 - B1" },
{ "name": "Level 2 - B2" }
]
}
]
}
]);
// 创建节点和连接
var node = chart.series.push(new am5xy ForceDirectedSeries.new(root, {
name: "Series",
layout: root => {
return am5 ForceDirectedTree.new(root, 1, 1);
},
nodeTemplate: (node, series) => {
var circle = node.shape = am5.Circle.new(root, 20);
circle.fill = am5.Color.new(root, 0xff0000);
circle.stroke = am5.Color.new(root, 0xffffff);
return circle;
},
linkTemplate: (link, series) => {
var line = link.shape = am5.Line.new(root, 2);
line.stroke = am5.Color.new(root, 0x0000ff);
return line;
}
}));
// 展开第一级子对象
node.nodes.each(node => {
if (node.dataItem.dataContext.children) {
node.isExpanded = true;
}
});
通过上述代码,你可以实现仅展开第一级子对象的效果。希望这个解答对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云