d3:power-scales

by Richard Hunter

HTML

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

CSS

svg {
  background: #fff1e5;
}

JavaScript

const margins = {
  top: 20,
  bottom: 20,
  left: 40,
  right: 20,
};

const width = 400;
const height = 400;

const data = [
  [0, 0],
  [1, 1],
  [2, 4],
  [3, 9],
  [4, 16],
  [5, 25],
  [6, 36],
  [7, 49],
  [8, 64],
  [9, 81],
  [10, 100]
];

const svg = renderSVG(width, height);

const xScale = d3.scalePow()
  .exponent(2)
  .domain([0, 10])
  .range([margins.left, width - margins.right])

const yScale = d3.scalePow()
  .exponent(2)
  .domain([0, 100])
  .range([height - margins.bottom, margins.top])

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

function renderSVG(width, height) {
  return d3.select('body')
    .append('svg')
    .attr('width', width)
    .attr('height', height);
}

function createLine(xScale, yScale) {
  return d3.line()
    .x(function(d) {
      return xScale(d[0]);
    })
    .y(function(d) {
      return yScale(d[1]);
    });
}

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

svg.append('g')
  .attr('transform', `translate(${margins.left}, 0)`)
  .call(yAxis)

svg.append('path')
	.datum(data)
  .attr('d', createLine(xScale, yScale))
  .attr('stroke', 'red')
  .attr('fill', 'none')