加载JSON代替CSV D3

时间:2015-07-15 20:40:43

标签: javascript json csv d3.js

我目前正在努力分拆d3noob页面:http://www.d3noob.org/2014/07/d3js-multi-line-graph-with-automatic.html

除了两个元素外,它几乎是一个完全相同的副本。一,我试图加载JSON文件而不是D3Noob的首选CSV。我还想知道使用扁平或嵌套的JSON文件是否更容易。如果嵌套会更好,有人可以解释或指导我到某个地方解释d3中的嵌套JSON比我一直在寻找的更好吗?那太棒了。

总结一下。 1.如何加载JSON代替CSV 2.嵌套还是扁平?

Nested Data

Flat Data

提前谢谢!

代码:

<!DOCTYPE html>
<html>
<meta charset="utf-8">

<head>
    <style> /* set the CSS */

    body { font: 12px Arial;}

    path { 
        stroke: steelblue;
        stroke-width: 2;
        fill: none;
    }

    .axis path,
    .axis line {
        fill: none;
        stroke: none;
        stroke-width: 1;
        shape-rendering: crispEdges;
    }
    .axis text {
        fill:red;
    }

    .legend {
        font-size: 16px;
        font-weight: bold;
        text-anchor: middle;
    }

    </style>
    <script src="d3.js"></script>

    <script>
    function init(){
        // Set the dimensions of the canvas / graph
        var margin = {top: 30, right: 20, bottom: 70, left: 50},
            width = 600 - margin.left - margin.right,
            height = 300 - margin.top - margin.bottom;

        // Set the ranges
        var x = d3.time.scale().range([0, width]);
        var y = d3.scale.linear().range([height, 0]);

        // Define the axes
        var xAxis = d3.svg.axis().scale(x)
            .orient("bottom").ticks(5);

        var yAxis = d3.svg.axis().scale(y)
            .orient("left").ticks(5);

        // Define the line
        var valline = d3.svg.line()   
            .x(function(d) { return x(d.week); })
            .y(function(d) { return y(d.val); });

        // Adds the svg canvas
        var svg = d3.select("body")
            .append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
            .append("g")
                .attr("transform", 
                      "translate(" + margin.left + "," + margin.top + ")");

        // Get the data
        d3.json("data.01.json", function(error, data) {
            data.chartdata.forEach(function(d) {
                d.week = d.week;
                d.val = +d.val;
            });

            // Scale the range of the data
            x.domain(d3.extent(data.chartdata, function(d) { return d.week; }));
            y.domain([0, d3.max(data.chartdata, function(d) { return d.val; })]);

            // Nest the entries by name
            var dataNest = d3.nest()
                .key(function(d) {return d.name;})
                .entries(data.chartdata);

            var color = d3.scale.category10();   // set the colour scale

            legendSpace = width/dataNest.length; // spacing for the legend

            // Loop through each name / key
            dataNest.forEach(function(d,i) { 

                svg.append("path")
                    .attr("class", "line")
                    .style("stroke", function() { // Add the colours dynamically
                        return d.color = color(d.key); })
                    .attr("id", 'tag'+d.key.replace(/\s+/g, '')) // assign ID
                    .attr("d", valline(d.values));

                // Add the Legend
                svg.append("text")
                    .attr("x", (legendSpace/2)+i*legendSpace)  // space legend
                    .attr("y", height + (margin.bottom/2)+ 5)
                    .attr("class", "legend")    // style the legend
                    .style("fill", function() { // Add the colours dynamically
                        return d.color = color(d.key); })
                    .on("click", function(){
                        // Determine if current line is visible 
                        var active   = d.active ? false : true,
                        newOpacity = active ? 0 : 1; 
                        // Hide or show the elements based on the ID
                        d3.select("#tag"+d.key.replace(/\s+/g, ''))
                            .transition().duration(100) 
                            .style("opacity", newOpacity); 
                        // Upweek whether or not the elements are active
                        d.active = active;
                        })  
                    .text(d.key); 

            });

            // Add the X Axis
            svg.append("g")
                .attr("class", "x axis")
                .attr("transform", "translate(0," + height + ")")
                .call(xAxis);

            // Add the Y Axis
            svg.append("g")
                .attr("class", "y axis")
                .call(yAxis);

        });
    }
    </script>
</head>
<body onload="init()">

<!-- load the d3.js library -->    

</body>
</html>

1 个答案:

答案 0 :(得分:0)

答案很简单,我应该早点意识到这一点。虽然我正确地做了一切,但它没有用。我的问题是我的代码处于头脑中,我试图在没有身体存在的情况下将SVG附加到身体上。我唯一要做的就是将所有的head脚本放到一个函数中,然后在加载body时调用该函数。

<!DOCTYPE html>
<html>
<meta charset="utf-8">

<head>
    <style> /* set the CSS */

    body { font: 12px Arial;}

    path { 
        stroke: steelblue;
        stroke-width: 2;
        fill: none;
    }

    .axis path,
    .axis line {
        fill: none;
        stroke: none;
        stroke-width: 1;
        shape-rendering: crispEdges;
    }
    .axis text {
        fill:red;
    }

    .legend {
        font-size: 16px;
        font-weight: bold;
        text-anchor: middle;
    }

    </style>
    <script src="d3.js"></script>

    <script>
    function init(){
        // Set the dimensions of the canvas / graph
        var margin = {top: 30, right: 20, bottom: 70, left: 50},
            width = 600 - margin.left - margin.right,
            height = 300 - margin.top - margin.bottom;

        // Set the ranges
        var x = d3.time.scale().range([0, width]);
        var y = d3.scale.linear().range([height, 0]);

        // Define the axes
        var xAxis = d3.svg.axis().scale(x)
            .orient("bottom").ticks(5);

        var yAxis = d3.svg.axis().scale(y)
            .orient("left").ticks(5);

        // Define the line
        var valline = d3.svg.line()   
            .x(function(d) { return x(d.week); })
            .y(function(d) { return y(d.val); });

        // Adds the svg canvas
        var svg = d3.select("body")
            .append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
            .append("g")
                .attr("transform", 
                      "translate(" + margin.left + "," + margin.top + ")");

        // Get the data
        d3.json("data.01.json", function(error, data) {
            data.chartdata.forEach(function(d) {
                d.week = d.week;
                d.val = +d.val;
            });

            // Scale the range of the data
            x.domain(d3.extent(data.chartdata, function(d) { return d.week; }));
            y.domain([0, d3.max(data.chartdata, function(d) { return d.val; })]);

            // Nest the entries by name
            var dataNest = d3.nest()
                .key(function(d) {return d.name;})
                .entries(data.chartdata);

            var color = d3.scale.category10();   // set the colour scale

            legendSpace = width/dataNest.length; // spacing for the legend

            // Loop through each name / key
            dataNest.forEach(function(d,i) { 

                svg.append("path")
                    .attr("class", "line")
                    .style("stroke", function() { // Add the colours dynamically
                        return d.color = color(d.key); })
                    .attr("id", 'tag'+d.key.replace(/\s+/g, '')) // assign ID
                    .attr("d", valline(d.values));

                // Add the Legend
                svg.append("text")
                    .attr("x", (legendSpace/2)+i*legendSpace)  // space legend
                    .attr("y", height + (margin.bottom/2)+ 5)
                    .attr("class", "legend")    // style the legend
                    .style("fill", function() { // Add the colours dynamically
                        return d.color = color(d.key); })
                    .on("click", function(){
                        // Determine if current line is visible 
                        var active   = d.active ? false : true,
                        newOpacity = active ? 0 : 1; 
                        // Hide or show the elements based on the ID
                        d3.select("#tag"+d.key.replace(/\s+/g, ''))
                            .transition().duration(100) 
                            .style("opacity", newOpacity); 
                        // Upweek whether or not the elements are active
                        d.active = active;
                        })  
                    .text(d.key); 

            });

            // Add the X Axis
            svg.append("g")
                .attr("class", "x axis")
                .attr("transform", "translate(0," + height + ")")
                .call(xAxis);

            // Add the Y Axis
            svg.append("g")
                .attr("class", "y axis")
                .call(yAxis);

        });
    }
    </script>
</head>
<body onload="init()">

<!-- load the d3.js library -->    

</body>
</html>