【问题标题】:d3.js : group dynamic SVG elements based on datad3.js :根据数据对动态 SVG 元素进行分组
【发布时间】:2017-07-11 15:17:42
【问题描述】:

我确实有一个 d3.scaleTime() 作为 x 轴和带有日期的 JSON 数据,它应该在这个 x 轴上表示为 rect,以便将日期标记为“保留”。

简单的方法是

this.svg.selectAll('rect').data(dates).enter().each(function(d) {
   d3.select(this)
    .append("rect")
    .attr('height', desiredHeight) 
    .attr('width', desiredWidthFromTickToTick) 
    .attr('x', x(d.date));
}

但我想将rects 分组,如果他们有连续的日期,以便能够在 x 轴上移动组。

我所做/尝试的是在输入/每个功能中检查是否已经有一个日期为当前日期“下一个”的组。 如果没有,请创建一个新组并附加当前日期矩形。 如果有组,则获取组并将日期矩形附加到现有组。

但现在,问题是rects 不保留他们的数据和/或我无法将rect 正确添加到组中。

一些(伪)代码:

var rects = this.svg.selectAll('rect') .data(dates, function(dataElement) {
    return dataElement.id;
});

// add new date rects
rects.enter().each(function(dataElement) {

   var isNewDateGroup = true / false; // detect if date is "next" to another one

   if (isNewDateGroup)
   {
      var group = svg.append("g");

      var dateRect = d3.select(this)
                    .append("rect")
                    .attr('height', desiredHeight) 
                    .attr('width', desiredWidthFromTickToTick);

     group.append(function() {
        // works correctly, appends the rect and sets the data 
        return dateRect.select('rect').node();
     });

     // translate group to desired x(d.date)
   }

   else
   {
      var group = getGroupForDate();

      var dateRect = d3.select(this)
                    .append("rect")
                    .attr('height', desiredHeight) 
                    .attr('width', desiredWidthFromTickToTick) 
                    .attr('x', offsetToLastRectInGroup);

     group.append(function() {
        // does not work correctly, does not append the rect and does not set the data 
        return dateRect.select('rect').node();
     });
   }
});

基本上,如果我附加一个以上的 SVG 元素,则 enter 函数不起作用,因为数据和附加也会混淆。 任何提示,我如何对我的矩形进行分组?

【问题讨论】:

    标签: d3.js


    【解决方案1】:

    this question 上的回答帮助我解决了我的问题: 由于.select() 将数据传播到选定的元素,我只需要摆脱选择:

    var dateRect = d3.select(this)
                        .append("rect")
                        .attr('height', desiredHeight) 
                        .attr('width', desiredWidthFromTickToTick) 
                        .attr('x', offsetToLastRectInGroup);
    
         group.append(function() {
            return dateRect.node();
         });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      相关资源
      最近更新 更多