jquery - D3 可重复使用的图表功能创建多个图表

标签 jquery d3.js

我构建了一个可重用的图表函数(向 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.
        // 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);
});

然后,当涉及通过更新数据或更改其他属性来更新图表时,您可以采用统一的方法,非常接近您的实现:

$("#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); 
});

关于jquery - D3 可重复使用的图表功能创建多个图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15762580/

相关文章:

ajax - $.ajax 始终返回成功,即使有错误

jquery - 页面上未加载功能

javascript - 如何修复 d3 折线图的时间刻度?

javascript - 如何将图像添加到c3.js折线图

javascript - 带有 D3v 3.5.13 图例和工具提示的简单 D3 折线图错误

javascript - d3js条形图中Y轴的一些文本剪切

jquery - 如何在使用带滚动的表格单元格时设置动态高度?

javascript - 如何允许用户通过检查文本框中的某些规则来插入语法方程

javascript - 垂直折叠树形图

jquery - 检查鼠标是否位于弹出窗口上