javascript-d3How can I create a graph network using d3.js?
Creating a graph network using d3.js is relatively straightforward. The following example code block will create a simple graph network with nodes and links:
// Create a graph network
var nodes = [
{id: "node-1"},
{id: "node-2"},
{id: "node-3"}
];
var links = [
{source: nodes[0], target: nodes[1]},
{source: nodes[1], target: nodes[2]}
];
var width = 600;
var height = 400;
// Create a force simulation
var simulation = d3.forceSimulation(nodes)
.force("charge", d3.forceManyBody().strength(-200))
.force("link", d3.forceLink(links).distance(150))
.force("center", d3.forceCenter(width / 2, height / 2))
.on("tick", ticked);
// Create SVG
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// Create links
var link = svg.selectAll(".link")
.data(links)
.enter().append("line")
.attr("class", "link");
// Create nodes
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 5);
// Tick function
function ticked() {
link
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
This code will generate a graph network with three nodes and two links connecting them. The code consists of the following parts:
- Declaring the nodes and links of the graph network.
- Setting the width and height of the network.
- Creating a force simulation to determine the position of the nodes.
- Creating an SVG element to draw the graph.
- Drawing the links between the nodes.
- Drawing the nodes.
- Ticking the simulation to update the position of the nodes and links.
For more information on creating graph networks with d3.js, check out the d3.js documentation or the d3.js examples.
More of Javascript D3
- How can I use d3.js to create a zoom scale?
- How do I create a zoomable chart using d3.js?
- How do I create a zoomable line chart using d3.js?
- How do I install and use D3.js with Yarn?
- How do I set up the x axis in d3.js?
- How do I implement zooming in a d3.js visualization?
- How do I use the z-index property with d3.js?
- How do I create an x and y axis using d3.js?
- How do I create a world map using d3.js?
- How can I use d3.js with W3Schools?
See more codes...