【问题标题】:D3 conditionally append image OR circle element based on variableD3根据变量有条件地附加图像或圆形元素
【发布时间】:2021-01-23 06:56:35
【问题描述】:

我有一个 D3 散点图,我正在尝试添加选项以根据变量的值将图表查看为圆形或图像。

目前我可以将图表视为其中之一(只要我将其中一个注释掉)

这是附加图像的代码:

   svg.selectAll(".image")
  .data(data)
  .enter()
  .append("svg:image")
  .attr("x", xMap)
  .attr("y", yMap)
  .attr("width", logosize)
  .attr("height", logosize)
  .attr('transform', function(d) { return 'translate('+ -d.logosize/2 +',' + -d.logosize/2 + ')'; }   )
  .attr("xlink:href", function(d) {
    return d.brand_image;
  })

以及添加点的代码:

svg.selectAll(".dot")
  .data(data)
  .enter().append("circle")
  .attr("class", "dot")
  .attr("r", 3.5)
  .attr("cx", xMap)
  .attr("cy", yMap)
  .style("fill", function(d) {
    return color(cValue(d));
  })

变量是var displaytype = "image" // or "dot"

我试图做类似的事情:

    if (displaytype == "image") { return 
    
    //....code for images.....
    
    else    { return  
    
    
   //....code for dots.....
    
    }

任何帮助解决这个问题将不胜感激

谢谢

【问题讨论】:

    标签: d3.js


    【解决方案1】:

    您使用 if/else 的方法没有错。您需要记住的是,点和图像是我称之为“点”的等效表示。这意味着选择不应该区分圆和图像:它应该只选择点。这可以通过使用类选择器而不是标签选择器来完成。

    在您的情况下,代码使用了两个不同的类选择器:.dot 和 .image。您可以使用svg.selectAll('.point') 代替svg.selectAll('.image') 和svg.selectAll('.dot')。因此:

        const enterSelection = svg.selectAll(".point").data(data).enter();
        
        if (displaytype == "image") {
          enterSelection
            .append("svg:image")
            .attr("class", "point")
            .attr("x", xMap)
            .attr("y", yMap)
            .attr("width", logosize)
            .attr("height", logosize)
            .attr("transform", function (d) {
              return "translate(" + -d.logosize / 2 + "," + -d.logosize / 2 + ")";
            })
            .attr("xlink:href", function (d) {
              return d.brand_image;
            });
        } else {
          enterSelection
            .append("circle")
            .attr("class", "point")
            .attr("r", 3.5)
            .attr("cx", xMap)
            .attr("cy", yMap)
            .style("fill", function (d) {
              return color(cValue(d));
            });
        }
    

    【讨论】:

    • 您也可以使用父 g 来保存圆圈/图像,这将允许在没有新的 selectAll().data().enter().append() 循环的情况下将圆圈交换为图像,反之亦然。此外,如果 g 定位所有内容,它将进一步简化两者的交换 - 但不确定这是否超出了 OP 最终目标的范围。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 2018-02-08
    • 1970-01-01
    • 2014-12-29
    相关资源
    最近更新 更多