D3.js enter()对于svg形状动画已损坏,但更新和删除它们都很好

D3.js enter() broken for svg shape animation but updates and removes them fine

本文关键字:更新 删除 很好 已损坏 动画 enter js 对于 svg D3      更新时间:2023-09-26

在Malcom McLean的"D3提示和技巧"动态更新数据和散点图教程的基础上,我试图获取两个不同的csv数据,并通过动画为每个数据绘制点(使用两个html按钮)。

当用户点击任一按钮时,我的changeTask函数会相应地移动直线、轴和点,并删除新数据集中没有的任何额外点。

但是,不会添加新的点(例如,当新数据应该比当前数据具有更多的点时)。changeTask函数中的.enter()出现问题。如果你尝试我的代码和数据,你会注意到在点击重置时左边的点丢失了。

完整代码:

 <!DOCTYPE html>
<meta charset="utf-8">
<style>
body { font: 12px Arial;}
path { 
    stroke: red;
    stroke-width: 2;
    fill: none;
}
.axis path,
.axis line {
    fill: none;
    stroke: grey;
    stroke-width: 1;
    shape-rendering: crispEdges;
}
.grid .tick {
    stroke: lightgrey;
    opacity: 0.7;
}
.grid path {
    stroke-width: 0;
}
.area {
    fill: lightsteelblue;
    stroke-width: 0;
}
div.tooltip {   
    position: absolute;         
    text-align: center;         
    width: 60px;                    
    height: 28px;                   
    padding: 2px;               
    font: 12px sans-serif;      
    background: lightsteelblue; 
    border: 0px;        
    border-radius: 8px;         
    pointer-events: none;           
}
</style>
<body>
<div id="option">
    <input name="updateButton" 
           type="button" 
           value="Update" 
           onclick="changeData('update')" 
    />
    <input name="resetButton" 
           type="button" 
           value="Reset" 
           onclick="changeData('reset')" 
    />
</div>
<script type="text/javascript" src="http://d3js.org/d3.v3.js"></script>
<script>
var margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%y").parse;
var formatTime = d3.time.format("%e %B");
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
// define the axis
var xAxis = d3.svg.axis().scale(x)
    .orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y)
    .orient("left").ticks(5);
/* // define the area below the line
var area = d3.svg.area()
    .x(function(d) { return x(d.date); })
    .y0(height)
    .y1(function(d) { return y(d.close); }); */
// define the first line
var valueline = d3.svg.line()
    .interpolate("linear")
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.close); });
var div = d3.select("body").append("div")   
    .attr("class", "tooltip")               
    .style("opacity", 0);
// create the 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 + ")"
            );
// find x-axis start point
function make_x_axis() {
    return d3.svg.axis()
        .scale(x)
        .orient("bottom")
        .ticks(5)
}
// find y-axis start point
function make_y_axis() {
    return d3.svg.axis()
        .scale(y)
        .orient("left")
        .ticks(5)
}
original_data = "data2.csv"
// get and plot the data
d3.csv(original_data, function(error, data) {
  data.forEach(function(d) {
        d.date = parseDate(d.date);
        d.close = +d.close;
    });
    // Scale the range of the data
    x.domain(d3.extent(data, function(d) { return d.date; }));
    y.domain([0, d3.max(data, function(d) { return d.close; })]);
    // create the line
    svg.append("path")
        .attr("class", "line")
        .attr("d", valueline(data));
    // dot the points
    svg.selectAll("circle")
        .data(data)
        .enter()
        .append("circle")
        .attr("r", 3.5)
        .attr("cx", function(d) { return x(d.date); })
        .attr("cy", function(d) { return y(d.close); })
        .on("mouseover", function(d) {      
            div.transition()        
                .duration(200)      
                .style("opacity", .9);      
            div .html(formatTime(d.date) + "<br/>"  + d.close)  
                .style("left", (d3.event.pageX) + "px")     
                .style("top", (d3.event.pageY - 28) + "px");    
            })                  
        .on("mouseout", function(d) {       
            div.transition()        
                .duration(500)      
                .style("opacity", 0);   
        });
    // give the graph an x axis
    svg.append("g")         
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);
    svg.append("text")
        .attr("x", width / 2)
        .attr("y", height + margin.bottom)
        .style("text-anchor", "middle")
        .text("Date");
    // create the Y axis
    svg.append("g")         
        .attr("class", "y axis")
        .call(yAxis);
    svg.append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 0 - margin.left)
        .attr("x", 0 - (height / 2))
        .attr("dy", "1em")
        .style("text-anchor", "middle")
        .text("Value");
    // give the graph a title
    svg.append("text")
        .attr("x", (width / 2))
        .attr("y", 0 - (margin.top / 2))
        .attr("text-anchor", "middle")
        .style("text-decoration", "underline")
        .text("Value vs Date Graph")
    // create vertical tick marks
    svg.append("g")
        .attr("class", "grid")
        .attr("transform", "translate(0," + height + ")")
        .call(make_x_axis()
            .tickSize(-height, 0, 0)
            .tickFormat("")
        )
    // make horizontal tick marks
    svg.append("g")
        .attr("class", "grid")
        .call(make_y_axis()
            .tickSize(-width, 0, 0)
            .tickFormat("")
        )
}); 
// animation that changes the graph's data
function changeData(task) {
    // determine which dataset to use depending on purpose
    if (task == "update") {
        file = "scatterplot_update.csv";
    } else if (task == "reset") {
        file = original_data;
    }
    // Get the data again
    d3.csv(file, function(error, data) {
        data.forEach(function(d) {
            d.date = parseDate(d.date);
            d.close = +d.close;
        });
        // Scale the range of the data again 
        x.domain(d3.extent(data, function(d) { return d.date; }));
        y.domain([0, d3.max(data, function(d) { return d.close; })]);
        // Select the section we want to apply our changes to
        var svg = d3.select("body")
        var circle = svg.selectAll("circle").data(data)
        // Make the changes
        svg.select(".x.axis") // change the x axis
            .transition()
            .duration(750)
            .call(xAxis);
        svg.select(".y.axis") // change the y axis
            .transition()
            .duration(750)
            .call(yAxis);
        svg.select(".line")   // change the line
            .transition()
            .duration(750)
            .attr("d", valueline(data));
        // update existing circles
        circle.transition()
            .duration(750)
            .attr("cx", function(d) { return x(d.date); })
            .attr("cy", function(d) { return y(d.close); });
        // enter new circles
        circle.enter()
            .append("circle")
            .attr("r", 10)
            .attr("cx", function(d) { return x(d.date); })
            .attr("cy", function(d) { return y(d.close); });
        // remove old circles
        circle.exit().remove()
    });
}
</script>
</body>

数据集为:

data2.csv

date,close
1-May-12,58.13
30-Apr-12,53.98
27-Apr-12,67
26-Apr-12,89.7
25-Apr-12,99
24-Apr-12,130.28
23-Apr-12,166.7
20-Apr-12,234.98
19-Apr-12,345.44
18-Apr-12,443.34
17-Apr-12,543.7
16-Apr-12,580.13
13-Apr-12,605.23
12-Apr-12,622.77
11-Apr-12,626.2
10-Apr-12,628.44
9-Apr-12,636.23
5-Apr-12,633.68
4-Apr-12,624.31
3-Apr-12,629.32
2-Apr-12,618.63
30-Mar-12,599.55
29-Mar-12,609.86
28-Mar-12,617.62
27-Mar-12,614.48
26-Mar-12,606.98

scatterplot_update.csv:

date,close
10-May-12,99.55
8-May-12,0
6-May-12,67.62
4-May-12,64.48
2-May-12,60.98
1-May-12,58.13
30-Apr-12,53.98
27-Apr-12,67
26-Apr-12,89.7
25-Apr-12,99
24-Apr-12,90.28
23-Apr-12,106.7
20-Apr-12,94.98
19-Apr-12,85.44
18-Apr-12,73.34
17-Apr-12,53.7
16-Apr-12,50.13
13-Apr-12,65.23
12-Apr-12,62.77
11-Apr-12,66.2
10-Apr-12,68.44
9-Apr-12,66.23

非常感谢你的帮助。

因为您使用的数据函数没有提供键函数,所以D3只是将数据连接到具有相应索引的圆中。。。由于第二个数据集较小,因此没有新的圆进入场景。

要解决此问题,只需在两个数据函数调用中添加以下第二个参数:

...
.data(data, function(d) {return d.date;})

这将使D3使用每个数据的日期字段作为联接键。

发现问题!我使用谷歌浏览器的Webkit Inspector来查看哪里出了问题。在我的changeData函数中,我的svg选择器缺少.select("svg").select("g")——当然,这些点没有放在它们应该放的地方!

changeData函数中正确的var分配是:

// Select the section we want to apply our changes to 
var svg = d3.select("body").select("svg").select("g");
var circle = svg.selectAll("circle").data(data);