{
const svg = d3.create('svg')
.attr('width', width + 80)
.attr('height', height);
svg.append("g").call(xAxis, x, 'horsehpower');
svg.append("g").call(yAxis, y, 'weight (lbs)');
function drawPoints(data) {
svg.selectAll('circle')
.data(data)
.join('circle')
.attr('cx', d => x(d.horsepower))
.attr('cy', d => y(d.weight))
.attr('fill', d => carColor(d.origin))
.attr('r', 3);
}
drawPoints(carData);
const legend = svg.append('g')
.attr('transform', `translate(${width - margin.right},${margin.top})`);
const rows = legend.selectAll('g')
.data(origins)
.join('g')
.attr('transform', (d, i) => `translate(20, ${i * 20})`);
rows.append('rect')
.attr('width', 15)
.attr('height', 15)
.attr('stroke-width', 2)
.attr('stroke', d => carColor(d))
.attr('fill', d => carColor(d))
.on('click', onclick);
rows.append('text')
.attr('font-size', 15)
.attr('x', 20)
.attr('y', 7.5)
.attr('font-family', 'sans-serif')
.attr('dominant-baseline', 'middle')
.text(d => d);
const selected = new Map(origins.map(d => [d, true]));
function onclick(event, d) {
const isSelected = selected.get(d);
const square = d3.select(this);
square.attr('fill', d => isSelected ? 'white' : carColor(d));
selected.set(d, !isSelected);
drawPoints(carData.filter(d => selected.get(d.origin)));
}
return svg.node();
}