散点图不会更新圆圈数

时间:2013-04-17 21:44:28

标签: d3.js

所以这里是所有代码,在一个要点中,你可以将它保存为HTML文件并尝试:

https://gist.github.com/babakinks/5407967

所以从一开始我就假设散点图圈有一些默认数字,并且我完全绘制了散点图

var numDataPoints = 50;

然后在底部,我有这个监听器,用随机的新值重绘散点图,它可以工作.. 但是我想改进它,这样我可以在文本框中键入要绘制的圆圈数量,它应该绘制多个圆圈,并不总是与它开始的相同。但它不听我的意思!是的,它会使用新的随机值重新绘制圆圈但是它仍然绘制了与它最初相同的圆圈数。我不知道如何解决这个问题,我对D3.js很新。我期待它工作的方式是错的?

    //On click, update with new data            
    d3.select("#drawbtn")
        .on("click", function() {

1 个答案:

答案 0 :(得分:3)

您只需要添加enter()和remove()选项:

<!DOCTYPE html>
<html lang="en">
  <head>
        <meta charset="utf-8">
        <title>yguyghggjkgh</title>
        <script src="http://d3js.org/d3.v3.min.js"></script>
        <style type="text/css">

            .axis path,
            .axis line {
                fill: none;
                stroke: black;
                shape-rendering: crispEdges;
            }

            .axis text {
                font-family: sans-serif;
                font-size: 11px;
            }

        </style>
    </head>
    <body>

        <div>
          <input type="text" id="count" name="howmany">
          <input type="button" id="drawbtn" value="draw">
        </div>


        <script type="text/javascript">

            //Width and height
            var w = 500;
            var h = 300;
            var padding = 30;

            //Dynamic, random dataset
            var dataset = [];                                           //Initialize empty array
            var numDataPoints = 50;
            console.log("so we are here.")                                      
            var maxRange = Math.random() * 1000;                        //Max range of new values
            for (var i = 0; i < numDataPoints; i++) {                   //Loop numDataPoints times
                var newNumber1 = Math.floor(Math.random() * maxRange);  //New random integer
                var newNumber2 = Math.floor(Math.random() * maxRange);  //New random integer
                dataset.push([newNumber1, newNumber2]);                 //Add new number to array
            }

            //Create scale functions
            var xScale = d3.scale.linear()
                                 .domain([0, d3.max(dataset, function(d) { return d[0]; })])
                                 .range([padding, w - padding * 2]);

            var yScale = d3.scale.linear()
                                 .domain([0, d3.max(dataset, function(d) { return d[1]; })])
                                 .range([h - padding, padding]);

            //Define X axis
            var xAxis = d3.svg.axis()
                              .scale(xScale)
                              .orient("bottom")
                              .ticks(5);

            //Define Y axis
            var yAxis = d3.svg.axis()
                              .scale(yScale)
                              .orient("left")
                              .ticks(5);

            //Create SVG element
            var svg = d3.select("body")
                        .append("svg")
                        .attr("width", w)
                        .attr("height", h);

            //Create circles
            svg.selectAll("circle")
               .data(dataset)
               .enter()
               .append("circle")
               .attr("cx", function(d) {
                    return xScale(d[0]);
               })
               .attr("cy", function(d) {
                    return yScale(d[1]);
               })
               .attr("r", 2);

            //Create X axis
            svg.append("g")
                .attr("class", "axis")
                .attr("transform", "translate(0," + (h - padding) + ")")
                .call(xAxis);

            //Create Y axis
            svg.append("g")
                .attr("class", "axis")
                .attr("transform", "translate(" + padding + ",0)")
                .call(yAxis);


            //On click, update with new data            
            d3.select("#drawbtn")
                .on("click", function() {
                    //New values for dataset
                    var numValues = parseInt(document.getElementById('count').value, 10);
                    console.log(numValues);
                    var maxRange = Math.random() * 1000;                        
                    dataset = [];                                               //Initialize empty array
                    for (var i = 0; i < numValues; i++) {                       //Loop numValues times
                        var newNumber1 = Math.floor(Math.random() * maxRange);  //New random integer
                        var newNumber2 = Math.floor(Math.random() * maxRange);  //New random integer
                        dataset.push([newNumber1, newNumber2]);                 //Add new number to array
                    }

                    //Update scale domains
                    xScale.domain([0, d3.max(dataset, function(d) { return d[0]; })]);
                    yScale.domain([0, d3.max(dataset, function(d) { return d[1]; })]);

                    //Update all circles
                    svg.selectAll("circle")
                       .data(dataset)
                       .transition()
                       .duration(1000)
                       .attr("cx", function(d) {
                            return xScale(d[0]);
                       })
                       .attr("cy", function(d) {
                            return yScale(d[1]);
                       });

                    //Enter new circles
                    svg.selectAll("circle")
                       .data(dataset)
             .enter()
             .append("circle")
                       .attr("cx", function(d) {
                            return xScale(d[0]);
                       })
                       .attr("cy", function(d) {
                            return yScale(d[1]);
                       })
             .attr("r", 2);

                    // Remove old
                    svg.selectAll("circle")
                       .data(dataset)
             .exit()
             .remove()

                });


        </script>
    </body>
</html>