D3可重用图表function创建多个图表

我已经构建了一个可重复使用的图表function(给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)); }); 

我会将实现更改为可重用:

 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. // eg 'g' which contains axis, title, etc. // 'Update' the rest of the graph here. // eg 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); }); 

现在有一个框架可以创建可重复使用的d3图表(基于Mike Bostock的文章 – http://bost.ocks.org/mike/chart/ ):

d3.chart

关于此的广泛文​​章 – http://weblog.bocoup.com/reusability-with-d3/和http://weblog.bocoup.com/introducing-d3-chart/