Here is code that will create a simple D3 bar chart based on an array of numbers.
const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9]; const w = 500; const h = 100; const svg = d3.select("#plot") .append("svg") .attr("width", w) .attr("height", h); svg.selectAll("rect") .data(dataset) .enter() .append("rect") .attr("x", (d, i) => i * 30) .attr("y", (d, i) => h - 3 * d) .attr("width", 25) .attr("height", (d, i) => 3 * d) .attr("fill", "blue")
This will create a very simple bar graph using the numbers in the array to determine the height of the bar. In order for this visualization to be displayed on my webpage here, we need to have a div with an id of “plot” and we need to import the D3 library.
So this is a very simple example that I took from my work at freeCodeCamp. You can do much more with D3 and as I develop more examples I’ll start adding them to this post.