D3.js (Data-Driven Documents) is a powerful JavaScript library for creating dynamic and interactive visualizations in the browser. In this guide, we’ll walk you through the process of building a scatterplot featuring circles and triangles with dynamic axes, styling, and interactivity using D3.js v3.
By the end of this tutorial, you'll have a functional scatterplot that meets the following specifications:
Before starting, ensure you:
Create a folder structure for your project:
[your name-hw3]
d3/
d3.v3.min.js
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>[YOUR NAME]</title> <script src="d3/d3.v3.min.js"></script> <style> svg { border: 1px solid black; } </style> </head> <body> <h1 style="text-align: center;">[YOUR NAME]</h1> <div id="scatterplot"></div> <script src="script.js"></script> </body> </html>
Set up the canvas for the scatterplot.
const width = 500, height = 500, padding = 50; const svg = d3.select("#scatterplot") .append("svg") .attr("width", width + padding * 2) .attr("height", height + padding * 2) .append("g") .attr("transform", `translate(${padding}, ${padding})`);
Generate 50 random objects (25 circles, 25 triangles) with random positions and sizes.
const data = Array.from({ length: 50 }, (_, i) => ({ x: Math.random() * 100, y: Math.random() * 100, size: Math.random() * (50 - 5) + 5, type: i < 25 ? "circle" : "triangle" })); const avgSize = d3.mean(data, d => d.size);
Define scales for mapping data values to screen coordinates and object sizes.
const xScale = d3.scale.linear().domain([0, 100]).range([0, width]); const yScale = d3.scale.linear().domain([0, 100]).range([height, 0]); const sizeScale = d3.scale.linear().domain([0, 100]).range([5, 50]);
Create dynamic axes that adjust to the data.
const xAxis = d3.svg.axis().scale(xScale).orient("bottom"); const yAxis = d3.svg.axis().scale(yScale).orient("left"); svg.append("g") .attr("transform", `translate(0, ${height})`) .call(xAxis); svg.append("g") .call(yAxis);
Plot circles and triangles on the scatterplot, applying colors based on their size.
svg.selectAll(".object") .data(data) .enter() .append("path") .attr("d", d3.svg.symbol().type(d => d.type === "circle" ? "circle" : "triangle-up").size(d => sizeScale(d.size))) .attr("transform", d => `translate(${xScale(d.x)}, ${yScale(d.y)})`) .attr("stroke", d => d.size > avgSize ? "blue" : "green") .attr("fill", "none");
Package your project as [your name-hw3].zip containing:
[your name-hw3].zip