首页 > 解决方案 > 如何使点从a移动到b

问题描述

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

我目前绘制点的散点图在这里

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

    // 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")
}

提前感谢您的任何帮助!

标签: javascriptd3.js

解决方案


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

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');

推荐阅读