如何在 d3 中的同一图上绘制多个矩形

How do I plot multiple rectangles on the same plot in d3

本文关键字:绘制 d3      更新时间:2023-09-26

我正在尝试使用 csv 文件中的数据在单个绘图上创建多个矩形。使用我目前的方法,我似乎正在为每行数据创建多个图。我怀疑我的问题与我如何选择和附加有关数据的 svg 元素有关。

d3.csv('Input/test_single.csv')
  .row(function (d) { return d })
  .get(function (error, rows) {
    var chart = d3.select("#chart-div").data(rows).enter().append("svg").classed("chart", true).attr("width", width);
    chart.append("rect")
         .attr("x", function(d){return(parseInt(d.Start) + parseInt(spacer))})
         .attr("y", 75)
         .attr("width", function(d){return(parseInt(d.End) - parseInt(d.Start))}) 
         .attr("height", 50)
         .style("stroke", "rgb(255,0,0)")
         .style("stroke-width", 2)
});

阅读连接思维,您正在做的是创建多个svg节点,而不是具有多个矩形的单个svg

d3.csv('Input/test_single.csv')
  .row(function (d) { return d })
  .get(function (error, rows) {
    var chart = d3.select("#chart-div").append('svg').classed("chart", true).attr("width", width)
    chart.selectAll('rect').data(rows)
      .enter()
      .append("rect")
      .attr("x", function(d){return(parseInt(d.Start) + parseInt(spacer))})
      .attr("y", 75)
      .attr("width", function(d){return(parseInt(d.End) - parseInt(d.Start))}) 
      .attr("height", 50)
      .style("stroke", "rgb(255,0,0)")
      .style("stroke-width", 2)
});