1

再利用可能なチャート関数を作成しました (Mike Bostock への帽子のヒント - http://bost.ocks.org/mike/chart/ ):

function chartBubble() {
  var width = 800,
      height = 800; 

  function chart() {
   var svg = d3.select("#chart").append("svg")
            .attr("width", width)
            .attr("height", height); 

   // generate rest of chart here
  }

  chart.width = function(value) {
    if (!arguments.length) return width;
    width = value;
    return chart;
  };

  return chart;
}

これは、関数を呼び出すことにより、最初はうまく機能します。

d3.csv("data.csv", function (data) {
 d3.select("#chart")
  .datum(data)
  .call(chartBubble().width(800));
});

重複した svg チャート オブジェクトを作成する問題は、次のように呼び出して幅を変更したいときに発生します。

$("#button").click(function(){
  d3.select("#chart")
   .call(chartBubble().width(500)); 
});
4

2 に答える 2

6

より再利用しやすいように実装を変更します。

function chartBubble() {
  var width = 800,
      height = 800; 

  function chart(selection) {
    selection.each(function (d, i) {
        var chartElem = d3.select(this);
        var svg = chartElem.selectAll('svg').data([d]);

        var svgEnter = svg.enter().append('svg');

        // Now append the elements which need to be inserted
        // only once to svgEnter.
        // e.g. 'g' which contains axis, title, etc.

        // 'Update' the rest of the graph here.
        // e.g. set the width/height attributes which change:
        svg
           .attr('width', width)
           .attr('height', height);

    });
  }

  chart.width = function(value) {
    if (!arguments.length) return width;
    width = value;
    return chart;
  };

  return chart;
}

次に、ほぼ同じ方法でチャートを作成します。

// Bubble is created separately and is initialized
var bubble = chartBubble().width(800);

d3.csv("data.csv", function (data) {
 d3.select("#chart")
  .datum(data)
  .call(bubble);
});

次に、 を更新するか、他の属性を変更してチャートを更新dataする場合、実装に非常に近い統一された方法があります。

$("#button").click(function(){
  // The advantage of defining bubble is that we can now change only
  // width while preserving other attributes.
  bubble.width(500);
  d3.select("#chart")
  //.datum(newData)
    .call(bubble); 
});
于 2013-04-02T21:16:27.647 に答える
1

現在、再利用可能な d3 チャートを作成できるフレームワークがあります (Mike Bostock の記事に基づく - http://bost.ocks.org/mike/chart/ ):

d3.チャート

これに関する広範な記事 - http://weblog.bocoup.com/reusability-with-d3/およびhttp://weblog.bocoup.com/introducing-d3-chart/

于 2013-09-16T07:13:13.707 に答える