0

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>D3 Area Chart</title>
</head>

<body>
    <div id="chart"></div>
    <script src="https://d3js.org/d3.v4.js"></script>
    <script>
        var data = [
        { date: 1990, num: 62 },
        { date: 1991, num: -34 },
        { date: 1992, num: -29 },
        { date: 1993, num: 69 },
        { date: 1994, num: -10 },
        { date: 1995, num: -21 }
        ];
        var time_parse = d3.timeParse("%Y");
        var time_format = d3.timeFormat("%Y");
        var chart_width = 600;
        var chart_height = 400;
        var padding = 50;

        data.forEach(function (e, i) {
            data[i].date = time_parse(e.date);
        });

        var x_scale = d3
            .scaleTime()
            .domain([
                d3.min(data, function (d) {
                    return d.date;
                }),
                d3.max(data, function (d) {
                    return d.date;
                })
            ])
            .range([padding, chart_width - padding]);
        var y_scale = d3
            .scaleLinear()
            .domain([
                d3.min(data, function (d) {
                    return d.num;
                }),
                d3.max(data, function (d) {
                    return d.num;
                })
            ])
            .range([chart_height - padding, padding]);

        var svg = d3
            .select("#chart")
            .append("svg")
            .attr("width", chart_width)
            .attr("height", chart_height);

        var red_area = d3
            .area()
            .defined(function (d) {
                return d.num < 0;
            })
            .x(function (d) {
                return x_scale(d.date);
            })
            .y0(function (d) {
                return y_scale(0);
            })
            .y1(function (d) {
                return y_scale(d.num);
            });
        svg
            .append("path")
            .datum(data)
            .attr("fill", "#E82C0C")
            .attr("d", red_area);

        var x_axis = d3
            .axisBottom(x_scale)
            .ticks(10)
            .tickFormat(time_format);
        var y_axis = d3.axisLeft(y_scale).ticks(12);
        svg
            .append("g")
            .attr("transform", "translate(0," + (chart_height - padding) + ")")
            .call(x_axis);
        svg
            .append("g")
            .attr("transform", "translate(" + padding + ",0)")
            .call(y_axis);

    </script>
</body>

</html>
|