line-chart

Interactive Line Chart

A native SVG line chart powered by built-in sample data.

This demo turns built-in sample data into an SVG path. Pointer movement finds the nearest data point and updates the label.

Source
const data = [18, 22, 19, 28, 34, 31, 42, 39, 48, 51, 47, 58];
const points = data.map((value, index) => ({
  x: 36 + (index / (data.length - 1)) * 648,
  y: 324 - ((value - Math.min(...data)) / (Math.max(...data) - Math.min(...data))) * 288,
  value,
}));

svg.addEventListener('pointermove', (event) => {
  const x = ((event.clientX - svg.getBoundingClientRect().left) / svg.clientWidth) * 720;
  const nearest = points.reduce((best, point) =>
    Math.abs(point.x - x) < Math.abs(best.x - x) ? point : best,
  );
  tooltip.textContent = nearest.value;
});