const dataset = [
{
"Type": "Fruit",
"Variety": "Apple",
"Category": "Fresh Fruits"
},
{
"Type": "Vegetable",
"Variety": "Carrot",
"Category": "Fresh Vegetables"
},
{
"Type": "Berry",
"Variety": "Blueberry",
"Category": "Berries"
}
];
const treeData = {
name: "My Produce Tree",
children: []
};
dataset.forEach((item) => {
let currentNode = treeData;
["Category", "Type", "Variety"].forEach((key) => {
let childNode = currentNode.children.find((child) => child.name === item[key]);
if (!childNode) {
childNode = { name: item[key], children: [] };
currentNode.children.push(childNode);
}
currentNode = childNode;
});
});
const width = 800;
const height = 600;
const svg = d3.select("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(40,0)");
const tree = d3.tree().size([height, width - 160]);
const root = d3.hierarchy(treeData);
tree(root);
const link = svg.selectAll(".link")
.data(root.links())
.enter().append("path")
.attr("class", "link")
.attr("d", d3.linkHorizontal()
.x((d) => d.y)
.y((d) => d.x));
const node = svg.selectAll(".node")
.data(root.descendants())
.enter().append("g")
.attr("class", "node")
.attr("transform", (d) => `translate(${d.y},${d.x})`);
node.append("circle")
.attr("r", 4.5);
node.append("text")
.attr("dy", ".31em")
.attr("x", (d) => d.children ? -13 : 13)
.style("text-anchor", (d) => d.children ? "end" : "start")
.text((d) => d.data.name);
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 1.5px;
}
.node text {
font: 12px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 1.5px;
}
<script src="https://d3js.org/d3.v7.min.js"></script>
<svg width="960" height="600"></svg>