d3:scatter-plot

by Richard Hunter

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js"></script>

CSS

svg {
  background: oldlace;
}

JavaScript

const data = [
  [1, 5],
  [4, 8],
  [67, 23],
  [2, 68],
  [12, 83],
  [4, 8],
  [98, 12],
  [56, 23],
  [95, 25],
  [38, 79],
  [11, 78],
  [76, 90],
  [25, 56],
  [16, 86],
];

const width = 600;
const height = 300;

const margin = {
  top: 30,
  right: 50,
  bottom: 40,
  left: 50,
};

const xScale = d3.scaleLinear()
  .domain([
    d3.min(data, d => d[0]),
    d3.max(data, d => d[0]),
  ])
  .range([0, width])

const yScale = d3.scaleLinear()
  .domain([
    d3.min(data, d => d[1]),
    d3.max(data, d => d[1])
  ])
  .range([
    height, 0
  ]);

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})`)

const xAxis = d3.axisBottom(xScale).ticks(20);
const yAxis = d3.axisLeft(yScale).ticks(20);

svg.selectAll('circle')
.data(data)
.enter()
.append('circle')
.attr('cx', d => xScale(d[0]))
.attr('cy', d => yScale(d[1]))
.attr('r', 2)
.attr('fill', 'chocolate')

svg.append('g')
  .attr('transform', `translate(0, ${height})`)
  .call(xAxis);

svg.append('g')
  .call(yAxis);