<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>learn d3 domain and range.</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.9.2/d3.min.js"></script>
    <style>
        .line {
            fill: none;
            stroke: aqua;
            stroke-width: 1;
        }
    </style>
</head>
<body>
    <div id="container">
        <h1>learn d3 domain and range.</h1>
        <svg width="800" height="600"></svg>
    </div>
    <script>
        var data = [-30,7,0,99,-12,0,120]
        var line_generator1 = d3.line()
            .x((d, i) => xrange(i))
            .y(d => yrange1(d))

        var line_generator2 = d3.line()
            .x((d, i) => xrange(i))
            .y(d => yrange2(d))

        var width = 400;
        var height = 400;

        var min = d3.min(data);
        var max = d3.max(data);
        var absMax = Math.max(Math.abs(min), Math.abs(max))

        var xrange = d3.scaleLinear().domain([0, data.length - 1]).range([0, width])

        var yrange1 = d3.scaleLinear().domain([-absMax, absMax]).range([0, height / 2])
        var yrange2 = d3.scaleLinear().domain([-absMax, absMax]).range([0, height])

        d3.select('svg')
            .append('g')
            .attr('transform', 'translate(30, 50)')

        d3.select('g')
            .append('path')
            .attr('d', line_generator1(data))
            .attr('class', 'line line-1')

        d3.select('g')
            .append('path')
            .attr('d', line_generator2(data))
            .attr('class', 'line line-2')
            .attr('transform', 'translate(0, -' + (height - height / 2) / 2 + ')')
    </script>
</body>
</html>

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.