如何将点从a移动到b

时间:2020-02-11 15:02:54

标签: javascript d3.js

我有一个散点图,我有两个从数据集中可视化的不同数据点集。我想为从“红色”到“蓝色”点的路径设置动画,并显示它们就像蓝色点正在从红色移动并获得其位置一样。 d3有可能吗?如果可以,我该怎么做?

我目前绘制的点的散点图是here

这是我在散点图中绘制两组数据点的方式:

    // blue dots
    svg.append('g')
        .selectAll("dot")
        .data(data)
        .enter()
        .append("circle")
        .attr("cx", function (d) { return x(d.x); } )
        .attr("cy", function (d) { return y(d.y); } )
        .attr("r", 4.1)
        .transition()
        .style("fill", "blue")



    // red dots
    svg.append('g')
        .selectAll("dot")
        .data(data)
        .enter()
        .append("circle")
        .attr("cx", function (d) { return x(d.x1); } )
        .attr("cy", function (d) { return y(d.y1); } )
        .attr("r", 4.1)
        .style("fill", "red")
}

谢谢您提前提供任何帮助!

1 个答案:

答案 0 :(得分:2)

是可能的。 使用属性转换并结合持续时间(以毫秒为单位)。看下面:

https://jsfiddle.net/mathyaku/L5bpaxwv/1/

function drawScatterplot(data, selector) {
  // set the dimensions and margins of the graph
  var margin = { top: 10, right: 30, bottom: 30, left: 60 },
    width = 700 - margin.left - margin.right,
    height = 700 - margin.top - margin.bottom;

  // append the svg object to the body of the page
  var svg = d3.select(selector)
    .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 + ")");

  //Read the data
  // Add X axis
  var x = d3.scaleLinear()
    .domain([0, 1])
    .range([0, width]);
  svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x));

  // Add Y axis
  var y = d3.scaleLinear()
    .domain([0, 1])
    .range([height, 0]);
  svg.append("g")
    .call(d3.axisLeft(y));


  // Add red dots
  svg.append('g')
    .selectAll("dot")
    .data(data)
    .enter()
    .append("circle")
    .attr("cx", function (d) { return x(d.x1); })
    .attr("cy", function (d) { return y(d.y1); })
    .attr("r", 4.1)
    .style("fill", "red")

  svg.selectAll("circle")
    .transition()
    .duration(2000)
    .attr("cx", function (d) { return x(d.x); })
    .attr("cy", function (d) { return y(d.y); })
    .style("fill", "blue")


}

drawScatterplot(data, '#Scatterplot');
相关问题