Clean β’ Professional
D3.js (Data-Driven Documents) is a powerful JavaScript library for creating dynamic, interactive, and highly customizable data visualizations using HTML, SVG, and CSS.
Unlike chart libraries like Google Charts or Chart.js, D3 gives full control over every visual element, making it ideal for complex and unique visualizations.
1. Include D3.js in Your Project
<script src="<https://d3js.org/d3.v7.min.js>"></script>
2. Select an HTML Element
D3 uses CSS-style selectors to target elements:
d3.select("body").append("p").text("Hello D3!");
select() β Selects the first matching elementselectAll() β Selects all matching elementsappend() β Adds new elementstext() β Adds text contentD3 binds data to DOM elements using data():
const data = [10, 20, 30, 40, 50];
d3.select("body")
.selectAll("p")
.data(data)
.enter()
.append("p")
.text(d => "Value: " + d);
data() β Binds an array of dataenter() β Creates new elements for each data pointd β Represents the current data item<div id="chart"></div>
<script>
const data = [80, 120, 60, 150, 200];
const width = 500;
const height = 300;
const svg = d3.select("#chart")
.append("svg")
.attr("width", width)
.attr("height", height);
svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", (d, i) => i * 60)
.attr("y", d => height - d)
.attr("width", 50)
.attr("height", d => d)
.attr("fill", "teal");
</script>
x β horizontal positiony β vertical position (SVG origin is top-left)height β height of each barfill β bar colorD3 provides scales to map data values to pixel values:
const xScale = d3.scaleBand()
.domain(data.map((d,i) => i))
.range([0, width])
.padding(0.1);
const yScale = d3.scaleLinear()
.domain([0, d3.max(data)])
.range([height, 0]);
svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", (d, i) => xScale(i))
.attr("y", d => yScale(d))
.attr("width", xScale.bandwidth())
.attr("height", d => height - yScale(d))
.attr("fill", "orange");
scaleLinear() β Maps numerical data to pixelsscaleBand() β Maps categorical/indexed data to bandsd3.axisBottom() and d3.axisLeft()