Unlocking Data-Driven Visualizations with D3 and TypeScript
Setting Up the Boilerplate Project
To get started, we need to set up our environment. We’ll write our HTML, CSS, and TypeScript code in a CodePen project.
import * as d3 from 'd3';
const svg = d3.select('body')
.append('svg')
.attr('width', 400)
.attr('height', 200);
svg.append('text')
.text('Hello, World!')
.attr('x', 10)
.attr('y', 20);
svg.append('circle')
.attr('cx', 50)
.attr('cy', 50)
.attr('r', 20);
This code creates a simple SVG element with a text label and a circle. We’ll build upon this foundation in the next sections.
Adding Data to Our Visualization
Data is the lifeblood of any visualization. We’ll use a CSV file to populate our visualization with data.
const csvData = [
{ x: 10, y: 20 },
{ x: 30, y: 40 },
{ x: 50, y: 60 },
];
const margin = { top: 10, right: 10, bottom: 10, left: 10 };
const width = 400 - margin.left - margin.right;
const height = 200 - margin.top - margin.bottom;
const svg = d3.select('body')
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', `translate(${margin.left}, ${margin.top})`);
svg.selectAll('circle')
.data(csvData)
.enter()
.append('circle')
.attr('cx', (d) => d.x)
.attr('cy', (d) => d.y)
.attr('r', 5);
This code reads the CSV data and creates a scatter plot with circles representing each data point.
Interacting with Our Visualization
The final step is to add interactivity to our visualization. We’ll create a button that removes one circle from the data when clicked.
const button = document.createElement('button');
button.textContent = 'Remove Circle';
document.body.appendChild(button);
button.addEventListener('click', () => {
csvData.pop();
svg.selectAll('circle')
.data(csvData)
.exit()
.transition()
.duration(500)
.attr('r', 0)
.remove();
});
This code creates a button that, when clicked, removes one circle from the data and updates the visualization accordingly.
With these steps, we’ve created a simple yet interactive data-driven visualization using D3 and TypeScript. This is just the tip of the iceberg, and there’s much more to explore in the world of data visualization.