Published
Edited
Dec 9, 2020
1 fork
Insert cell
md`# Scatter Plot Example 2`
Insert cell
{
const svg = DOM.svg(960,500);
const popChart = d3.select(svg)
const height = 500;
const width = 960;
const circleRadius = 10
const render = data => {
const xVal = d => d.horsepower;
const yVal = d => d.weight;
const margin = {top: 60,right: 40,bottom: 80, left: 150}
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
const xScale = d3.scaleLinear()
.domain(d3.extent(data,xVal))
.range([0,innerWidth])
.nice();
const yScale = d3.scaleLinear()
.domain(d3.extent(data,yVal))
.range([0,innerHeight]).nice()
const xAxis = d3.axisBottom(xScale).tickSize(-innerHeight).tickPadding(15);
const g = popChart.append('g')
.attr('transform',`translate(${margin.left},${margin.top})`);
const yAxis = d3.axisLeft(yScale).tickSize(-innerWidth).tickPadding(15)
const yAxisG = g.append('g')
.call(yAxis)
.style('font-size','1.1em')
.style('font-family','sans-serif')
yAxisG.selectAll('.domain')
.remove();
yAxisG.append('text')
.attr('y',-80)
.attr('x',-innerHeight/2)
.attr('fill','#635F5D')
.attr('transform','rotate(-90)')
.style('text-anchor','middle')
.text('Weight')
const xAxisG = g.append('g').call(xAxis)
.attr('transform',`translate(0,${innerHeight})`)
.style('font-size','1.1em')
.style('font-family','sans-serif');
xAxisG.select('.domain').remove();
xAxisG.append('text').attr('y',50).attr('x', innerWidth/2).attr('fill','#635F5D').text('Horsepower')
g.selectAll('circle').data(data)
.enter().append('circle')
.attr('cy',d=>yScale(yVal(d)))
.attr('cx',d=>xScale(xVal(d)))
.attr('r',circleRadius)
.attr('fill','red')
.style('opacity','0.3');
g.append('text').attr('y',-10)
.style('font-size','2em')
.style('font-family','sans-serif')
.text('Cars: Horsepower vs Weight');
g.selectAll('.tick text').attr('color','#635F5D');
g.selectAll('.tick line').attr('stroke','#C0C0BB');
}

d3.csv('https://vizhub.com/curran/datasets/auto-mpg.csv')
.then(data =>{
data.forEach(d=>{
d.mpg = +d.mpg;
d.cylinders = +d.cylinders;
d.displacement = +d.displacement;
d.horsepower = +d.horsepower;
d.weight = +d.weight;
d.acceleration = +d.acceleration;
d.year = +d.year;
});
render(data)
})
return svg
}
Insert cell
d3 = require('d3');
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more