【问题标题】:General update pattern, on new file upload old doesn't remove一般更新模式,新文件上传旧文件不会删除
【发布时间】:2019-09-18 02:31:11
【问题描述】:

我是 d3 的新手,所以我对一般更新模式有疑问(我研究了我在网上能找到的所有内容)。

所以,我正在创建网络应用程序,在其中我使用 FileAPI (getAsUrl) 从 PC 上传 .csv 数据,这部分工作正常,但是当我在第一个文件之后上传任何内容时,所有数据都显示在图表上,来自所有上传的 .csv -s。 目前唯一的解决方案是在新的上传刷新浏览器之前,但这对用户不友好!

任何帮助将不胜感激:)

P.S:如果是指我使用 Windows 的任何东西,IDE 是 VScode,图形是带有回归线的散点图。

// setting graph, it's not all code for graph
const svg = d3.select(".chart")
   .append("svg")
const x = d3.scaleLinear()
const y = d3.scaleLinear()


//uploading file

//reading in data to chart
function drawChart(url) {         

  //Read the data
   {

    d3.entries(dataset); // pretvara 'object' u 'array'

// Add dots
  var renderChart = (selection, {dataset}) => {
    let dots = selection.selectAll(".dot")
    .data(dataset);
    dots.join (
      enter =>
        enter
              .append("circle")
              .attr("cx", (d) => x(d.x))
              .attr("cy", (d) => y(d.y))
              .attr("r", 4)
              .attr("fill", "#69b3a2")
              .attr("opacity", 0.7)
    ),
      update =>
        update
          .attr("cx", (d) => x(d.x))
          .attr("cy", (d) => y(d.y))
          .attr("r", 4)
          .attr("fill", "#69b3a2")
          .attr("opacity", 0.7),
        dots
          .exit().remove();

    }
});
}  // that's just scatter plot, there is more code for regression

document.getElementById('file_input').addEventListener('change', getAsUrl, false); 



//in HTML file this is input for button
<input type="file" id="file_input" name="files[]" accept=".csv"  multiple />

正如我所写,在第一次上传 .csv 时一切正常,但在每次上传时,旧点会保留,新点只会添加。

【问题讨论】:

    标签: javascript d3.js fileapi


    【解决方案1】:

    您的join 结构不正确。根据documentation,应该是这样的:

    selection.join(enter[, update][, exit])
    

    如您所见,exit 选择是第三个参数(括号说明第二个和第三个参数都是可选的)。更明确地说,仍然根据相同的文档:

    .join(
        enter => enter.append("circle"),
        update => update,
        exit => exit.remove()//3rd argument
      )
    

    除了您的 update 部分也不正确之外,您可以看到它位于 join 方法之外。

    话虽如此,你的功能应该是:

    dots.join(
      enter => enter.append("circle")
      .attr("cx", (d) => x(d.x))
      .attr("cy", (d) => y(d.y))
      .attr("r", 4)
      .attr("fill", "#69b3a2")
      .attr("opacity", 0.7),
      update => update.attr("cx", (d) => x(d.x))
      .attr("cy", (d) => y(d.y))
      .attr("r", 4)
      .attr("fill", "#69b3a2")
      .attr("opacity", 0.7),
      exit => exit.exit().remove()
    );
    

    【讨论】:

    • 是的,你是对的,更新模式不像文档中那样,但是在我改变它之后什么也没发生。新数据仍然与旧数据重叠!
    • 那么你在其他地方还有另一个问题。我建议您使用minimal reproducible example 发布一个新问题。
    • 可能是 FileApi 出了什么问题。但是我输入了代码以一种颜色显示第一个上传的文件点,并在更新 d3 图表上显示其他颜色,但该部分也没有显示。 jsfiddle.net/gingerM/3Lyxkhbw
    猜你喜欢
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2022-07-15
    • 2021-08-16
    相关资源
    最近更新 更多