3

D3の結合に問題があります。バブルグラフ上にいくつかの円を作成しました。ユーザーが[地図として表示]ボタンをクリックしたときに、円を地図に変換してから、それぞれにラベルを追加します。

現在、クリックハンドラーは円をOKに移動し、ラベルを追加するのではなく、JavaScriptエラーを表示しますUncaught TypeError: Object [object SVGCircleElement]... has no method 'append'。これは結合構文が正しくないためですが、どうすれば修正できますか?

新しいD3要素を追加するために私が見つけることができるすべての例は、新しいデータをバインドしている場合のためのものです-データがすでにバインドされている既存の要素がすでにある場合ではありません。

これは、サークルを作成するための私のコードです。

  var circle = g.selectAll('.city')
     .data(data).enter()
     .append('circle')
    .attr('class', 'city')
    .attr('r', rfunc).attr("cy", 0)
    .attr("cx", function(d, i) {
      return rdist(d['dist']);
    }).attr("transform", function(d, i) {
      return "rotate(" + d.radial_pos + " 0 0)";
    });

そしてこれは私のクリックハンドラーです:

d3.select("#layout_geo").on("click", function() {
    // Move the circles - this works OK. 
    var circles = d3.selectAll(".city")
    .transition()
    .duration(1300)
    .attr('cx', function(d) {
       return merc([d['lon'], d['lat']])[0] - 350;
    }).attr('cy', function(d) {
      return merc([d['lon'], d['lat']])[1] - 280;
    });
    // How to add text to each circle?
    circles.append('text')
      .attr('class', 'background')
      .text(function(d) {
         console.log(d.name + ', ' + d.city);
          return d.name + ', ' + d.city;
      })
      .attr('cx', function() {
        return ???;
      }).attr('cy', function() {
        return ???;
      });
  });
4

1 に答える 1

3

ここでの問題は、circlesが通常の選択ではなく遷移であるということです。remove()アイテムを削除するのに便利な機能がありますが、append要素を追加することはできません。

もう1つの問題は、属性<text>に要素を追加することが正しいSVGではないことです。この場合、とをこのような要素の中に入れる必要があります。コードの対応する変更は次のようになります。<circle><text><circle>g

d3.select("#layout_geo").on("click", function() {
    // Assign the seleciton to circles
    var circleG = d3.selectAll(".city");

    circleG.transition()
      .duration(1300)
      .attr('transform', 'translate(-100, -50)'); // Ignoring the rotation.

    // And append text to the selection
    circleG.append('text')
      .attr('class', 'background')
      .attr('dx', '1em')
      .text(function(d) {
          console.log(d.name + ', ' + d.city);
          return d.name + ', ' + d.city;
      });
  });

属性<circle>を変更している間、要素の回転が失われることに注意してください。外側の要素を回転させてネストされた2つのg要素を使用transformすることで保存できます。

于 2013-01-22T14:07:45.463 に答える