d3:exercises

by Richard Hunter

HTML

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

CSS

svg {

}

.line {
  fill: none;
  stroke-width: 0.5;
}

.line.pressUps {
  stroke: teal;
}
.line.legLifts {
  stroke: dodgerblue;
}

JavaScript

// data needs to be sorted by date
const data = [{
    date: new Date('2023-07-02'),
    pressUps: 28,
    legLifts: 28,
    koreanDips: 30,
  },
  {
    date: new Date('2023-07-03'),
    pressUps: 30,
    legLifts: 29,
    koreanDips: 30,
  },
  {
    date: new Date('2023-07-08'),
    pressUps: 30,
    legLifts: 28,
    koreanDips: 30,
  },
  {
    date: new Date('2023-07-10'),
    pressUps: 120,
    legLifts: 230,
    koreanDips: 30,
  },
  {
    date: new Date('2023-07-14'),
    pressUps: 400,
    legLifts: 350,
    koreanDips: 30,
  },
];

const width = 500;
const height = 200;

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

const formatTime = d3.timeFormat('%d/%m/%y');

const xScale = createXScale(data);
const yScale = createYScale(data);

const xAxis = createXAxis(xScale);
const yAxis = createYAxis(yScale);

const pressUpsLine = createPressUpsLine(xScale, yScale);
const legLiftsLine = createLegLiftsLine(xScale, yScale);
const svg = renderSVG(width, height);

renderXAxis(svg, xAxis);
renderYAxis(svg, yAxis);

renderLine(data, pressUpsLine, 'pressUps');
renderLine(data, legLiftsLine, 'legLifts');

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

function createXScale(data) {
  return d3.scaleTime().domain([
    d3.min(data, d => d.date),
    d3.max(data, d => d.date),
  ]).range([margins.left, width - margins.right]);
}

function min(data) {
  return Math.min(data.pressUps, data.legLifts);
}

function max(data) {
  return Math.max(data.pressUps, data.legLifts);
}

function createYScale(data) {
  return d3.scaleLinear()
    .domain([
      d3.min(data, min),
      d3.max(data, max)
    ])
    .range([height - margins.bottom, margins.top])
}

function createXAxis(xScale) {
  return d3.axisBottom()
    .scale(xScale)
    .ticks(5)
    .tickFormat(formatTime);
}

function createYAxis(yScale) {
  return d3.axisLeft()
    .scale(yScale)
   ...