d3:line-chart

by Richard Hunter

HTML

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

CSS

svg {
  background: lightgoldenrodyellow;
}

.line {
  fill: none;
  stroke-width: 2;
  stroke: teal;
}

JavaScript

const width = 700;
const height = 400;

const margin = {
  top: 20,
  right: 15,
  bottom: 60,
  left: 60,
};

const JAN = 0;
const FEB = 1;
const MAR = 2;
const APR = 3;
const MAY = 4;
const JUN = 5;
const JUL = 6;
const AUG = 7;
const SEP = 8;
const OCT = 9;
const NOV = 10;
const DEC = 11;

const svg = d3.select("body").append("svg")
  .attr("width", width)
  .attr("height", height);

const data = [{
    x: new Date(2023, JAN, 12),
    y: 5
  },
  {
    x: new Date(2023, MAR, 14),
    y: 30
  },
  {
    x: new Date(2023, APR, 4),
    y: 23
  },
  {
    x: new Date(2023, MAY, 17),
    y: 4
  },
  {
    x: new Date(2023, JUN, 4),
    y: 7
  },
  {
    x: new Date(2023, AUG, 21),
    y: 8
  },
  {
    x: new Date(2024, FEB, 23),
    y: 12
  },
  {
    x: new Date(2024, JUL, 9),
    y: 21
  },
  {
    x: new Date(2024, SEP, 4),
    y: 34
  },
  {
    x: new Date(2024, OCT, 12),
    y: 18
  },
  {
    x: new Date(2024, DEC, 29),
    y: 15
  },
];

const xScale = d3.scaleTime()
  .domain([d3.min(data, d => d.x), d3.max(data, d => d.x)])
  .range([margin.left, width - margin.right])

const yScale = d3.scaleLinear()
  .domain([
    0,
    d3.max(data, d => d.y)
  ])
  .range([height - margin.bottom, margin.top]);

const xAxis = d3.axisBottom(xScale)
  .ticks(5)
  .tickFormat(d3.timeFormat('%B %Y'))

const yAxis = d3.axisLeft(yScale);

const lineFn = d3.line()
  .x(function(d) {
    return xScale(d.x);
  })
  .y(function(d) {
    return yScale(d.y);
  });

svg.append("path")
  .datum(data)
  .attr("d", lineFn)
  .attr('class', 'line');

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

svg.append('g')
  .attr('class', 'yAxisLabel')
  .append('text')
  .text('values')
  .attr('font-family', 'arial')
  .attr('font-size', 14)
  .attr('text-anchor', 'middle')
  .attr('transform', `translate(${margin.left / 2}, ${margin.top + ((height - margin.top -...