{
const width = 1000;
const height = 300;
const margin = {top:20, bottom: 35, left:35, right:5};
const radius = 2;
const data = cars;
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);
const scaleX = d3.scaleLinear().range([margin.left, width - margin.right]);
const scaleY = d3.scaleLinear().range([height - margin.bottom, margin.top]);
const axisX = svg.append('g')
.attr('transform', `translate(0, ${height - margin.bottom})`);
const labelX = axisX.append('text')
.attr('x', scaleX.range()[1])
.attr('y', margin.bottom - 5)
.style('fill', 'black')
.style('text-anchor', 'end');
const axisY = svg.append('g')
.attr('transform', `translate(${margin.left}, 0)`);
const labelY = axisY.append('text')
.attr('x', 0)
.attr('y', margin.top - 5)
.style('fill', 'black')
.style('text-anchor', 'middle');
let attributeX = 'power (hp)';
let attributeY = 'economy (mpg)';
const selectX = d3.select('#attributeX');
const selectY = d3.select('#attributeY');
selectX.selectAll('option')
.data(Object.keys(data[0]).filter(d => d != 'name'))
.join('option')
.text(d => d);
selectY.selectAll('option')
.data(Object.keys(data[0]).filter(d => d != 'name'))
.join('option')
.text(d => d);
selectX.on('change', function(e) {
attributeX = this.value;
draw_scatterplot();
});
selectY.on('change', function(e) {
attributeY = this.value;
draw_scatterplot();
});
draw_scatterplot();
function draw_scatterplot() {
scaleX.domain(d3.extent(data, d => d[attributeX]));
scaleY.domain(d3.extent(data, d => d[attributeY]));
axisX.call(d3.axisBottom(scaleX));
labelX.text(attributeX);
axisY.call(d3.axisLeft(scaleY))
labelY.text(attributeY);
svg.selectAll('circle')
.data(data)
.join('circle')
.attr('r', radius)
.attr('cx', d => scaleX(d[attributeX]))
.attr('cy', d => scaleY(d[attributeY]));
}
return svg.node();
}