chart = {
const width = 800;
const height = 700;
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.style("font", "12px sans-serif");
const color = d => ({
"bacteria": "#66c2a5",
"metabolite": "#fc8d62",
"symptom": "#8da0cb",
"diet": "#e78ac3",
"personal": "#a6d854"
}[d.group] || "#ccc");
const simulation = d3.forceSimulation(filteredNodes)
.force("link", d3.forceLink(filteredEdges).id(d => d.id).distance(80))
.force("charge", d3.forceManyBody().strength(-200))
.force("center", d3.forceCenter(width / 2, height / 2));
const link = svg.append("g")
.attr("stroke", "#aaa")
.attr("stroke-opacity", 0.6)
.selectAll("line")
.data(filteredEdges)
.join("line")
.attr("stroke-width", d => Math.sqrt(d.weight || 1))
.attr("stroke", d => d.color || "#999");
const node = svg.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 1.5)
.selectAll("circle")
.data(filteredNodes)
.join("circle")
.attr("r", 8)
.attr("fill", d => color(d))
.call(drag(simulation));
const label = svg.append("g")
.selectAll("text")
.data(filteredNodes)
.join("text")
.text(d => d.id)
.attr("x", 10)
.attr("y", 3);
node.append("title")
.text(d => `${d.id} (${d.group})`);
simulation.on("tick", () => {
link
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);
node
.attr("cx", d => d.x)
.attr("cy", d => d.y);
label
.attr("x", d => d.x + 10)
.attr("y", d => d.y + 3);
});
function drag(simulation) {
function dragstarted(event, d) {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(event, d) {
d.fx = event.x;
d.fy = event.y;
}
function dragended(event, d) {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
return d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
}
return svg.node();
}