D3可重用图表函数创建多个图表 [英] D3 Reusable Chart Function Creating Multiple Charts

查看:220
本文介绍了D3可重用图表函数创建多个图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立了一个可重复使用的图表函数(对于Mike Bostock的帽子提示 - http:// bost。 ocks.org/mike/chart/ ):

I've built a reusable chart function (hat tip to 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;
}

这可以通过调用函数来实现很好的初始化:

This works great initialy by calling the function:

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

当我想通过调用来改变宽度时会出现问题,它创建一个重复的svg图表对象:

The problem, which creates a duplicate svg chart object, arises when I want to change the width by calling:

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


推荐答案

可重复使用:

I would change the implementation to be more reusable:

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;
}

然后您将以同样的方式创建图表:

Then you would create the chart in much the same way:

// 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 或者通过改变其他属性,你有一个统一的方法,非常接近你的实现:

Then when it comes to updating the chart either by updating the data or by changing other attributes, you have a uniform way of doing it, very close to your implementation:

$("#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可重用图表函数创建多个图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆