D3 - 使用 D3 的 SVG 符号缩放

D3 - Zooming with D3's SVG Symbols

我想按照 fiddle 所示的以下方式放大我的节点。 http://jsfiddle.net/HF57g/2/

Fiddle 来源:How to zoom in/out d3.time.scale without scaling other shapes bound to timeline

在 fiddle 的帮助下,我能够使用 SVG 圆应用缩放。

注意:下面的代码表明,通过使用 SVG Circles,您将获得 x 轴和 y 轴属性。

.enter().append("circle")
.attr("cx", function(d) { return xScale(d); })
.attr("cy", function(d) { return yScale(d); })       

我想要的是使用此缩放功能同时拥有圆圈和菱形

所以我选择了 D3 的 "d3.svg.symbol",以允许圆形和菱形。

但是,我面临的问题是,通过使用 D3 的 SVG 符号,我无法专门操作 x 轴,因为它只允许平移。

.enter().append("path")
.attr("transform", function(d) {
      return "translate(" + d.x + "," + d.y + ")"; })
.attr("d", d3.svg.symbol()
             .size(145)
             .type(function(d) {
                          if(d.value <= 10)
                                 return "diamond";
                          else
                             return "circle";
                      })); 

下面来自 fiddle 的代码显示了对取自 fiddle 的缩放的 x 轴的操作。如果可能的话,我想对翻译做同样的事情。

return svg.selectAll("rect.item")
    .attr("x", function(d){return scale(d);}) 

下面的代码显示了它与 SVG Circles 一起工作的方式,它显示了我认为使缩放工作的最合乎逻辑的方式。但不幸的是它不起作用。

var zoom = d3.behavior.zoom()
           .on("zoom", function(){
           //If I use SVG Circles the following code works.
           //chart.selectAll(".item").attr("cx", function(d){ return xScale(d); });

           //By using SVG Symbols and translate, this does not work
           chart.selectAll(".item").attr("transform", function(d) { return  "translate("+ d.x +", 0)";});

            }).x(xScale);

这里是 fiddle 用菱形和圆圈编辑的。 https://jsfiddle.net/g67cgt4w/

https://jsfiddle.net/62vq9h8p/

在 update_events() 函数中,您不能将 "circleDiamond.item" 用作 select 或者因为您没有 <circleDiamond> 元素 - 有一个 <circle> svg 元素,这就是为什么你可以使用 "circle.myCircle" 的原因。您可以设置更好的 class,例如“.circle.diamond.item”。 select 他们。所以我改变了这个并添加了

var cy = d3.transform(d3.select(this).attr("transform")).translate[1];
return "translate(" + scale(d) + "," + cy +")";

这将保持当前的 Y 定位。

d3.transform(d3.select(this).attr("transform"))

采用当前元素的变换,.translate[1] 采用翻译对象和 returns Y 值(这是第二项)。如果取而代之的是 0 索引,则可以采用当前 X 值。