【问题标题】:Failing to transition in D3 off new data无法在 D3 中转换新数据
【发布时间】:2013-12-19 21:56:01
【问题描述】:

我可以完美地加载和显示一次数据,但任何更新尝试似乎都失败了。

我正在尝试构建显示活动的地图。在我的数据 csv 中,我有纬度和对数以及活动时间(0-23)。我在用新数据更新 D3 时使用 this highly useful tutorial。我的想法是按小时循环浏览数据。

我或多或少地窃取了更新功能。虽然初始调用运行良好,但任何重复调用只能重新着色已经存在的数据,而不是删除它并添加新数据。这让我相信我没有更改传入的数据。

我的更新调用有什么明显的问题吗?

function update(data, x) {
    // DATA JOIN
    // Join new data to any existing data
    var circles = g.selectAll("circle")
        .data(data); //, function(d) { return d; });

    // UPDATE
    // Update old elements as needed.
    circles
        .style("fill", "green")
            .transition()
            .duration(750);

    // ENTER
    // Create new elements
    circles.enter().append("circle")
        .filter(function(d) { return d.hr == x; })
        .attr("cx", function(d) {
            return projection([d.lon, d.lat])[0];
        })
        .attr("cy", function(d) {
            return projection([d.lon, d.lat])[1];
        })
        .attr("r", 0)
        .style("opacity", 0.2)
        .style("fill", "blue")
        .transition()
        .duration(750)
        .ease("linear")
        .attr("r", function(d) {
            return d.radius/2;
        });


    // EXIT
    // Remove old elements
    circles.exit()
        .style("fill", "red")
        .transition()
        .duration(1500)
        .ease("linear")
        .attr("r", 0)
        .remove();
}

从命令行运行:

update(csv_data, 1)
update(csv_data, 5)

【问题讨论】:

  • 您是否熟悉数据连接在 D3 中的工作方式?如果没有,我会看看this。因为您绝对不会更改传入数据:.data(data) 行设置选择的数据,并且根据您的函数调用,csv_data 在对update 的两次调用中都是相同的。
  • 我可以提供更多帮助(并写下答案),但我需要查看 csv_data 中的内容。
  • 我正在使用 d3.csv 来提取数据。格式为纬度、经度、半径、小时
  • 我得到了另外 3 个,但 hr 是什么?
  • 所以数据是一个对象数组,其中每个对象都具有您上面提到的 4 个属性?

标签: javascript json csv d3.js transition


【解决方案1】:

您似乎正在尝试按行更改数据

filter(function(d) { return d.hr == x; })

但这只是filtering the selection。

您要做的是过滤数据之前将其传递给您对行所做的选择

.data(data);

我建议在更新函数的开头使用Array.filter:

function update(data, x) {
    // DATA JOIN
    // Join new data to any existing data

    // filter the data as per x
    data = data.filter(function (d) { return d.hr == x; });

    var circles = g.selectAll("circle")
        .data(data);

    // rest of function
 }

请务必删除追加后过滤的行。

【讨论】:

  • 更近了!它肯定会增加和过渡。但是现在如果我以不同的顺序运行它,它就会变得很奇怪。例如运行 update() 0, 1, 2, 4 产生的点与运行它 4, 2, 1, 0 不同 我也不能回调,所以我不能去 0,2,0
猜你喜欢
  • 2013-04-01
  • 1970-01-01
  • 2012-08-02
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多