【问题标题】:Multiple NVD3 charts on page. How to simplify the javascript code and wrap function?页面上有多个 NVD3 图表。如何简化javascript代码和包装功能?
【发布时间】:2014-08-06 20:06:25
【问题描述】:

我目前在网站上使用 NVD3 来绘制图表,其中一个页面有 6 个图表。我目前只为六个图表中的每一个添加了 6 个函数,但我觉得这不是解决问题的最优雅的方法。下面是相关的html/javascript代码示例:

<div id="chicago" class='with-3d-shadow with-transitions chart'>
  <svg> </svg>
</div>

nv.addGraph(function() {
  var chicago = nv.models.lineChart()
      .margin({top: 30, right: 60, bottom: 50, left: 80})
      .x(function(d,i) { return i })
      .color(d3.scale.category10().range());

  chicago.transitionDuration(500);

  chicago.xAxis.tickFormat(function(d) {

      var dx = testdata[0].values[d] && testdata[0].values[d].x || 0;
      if (dx > 0) {
          return d3.time.format('%x')(new Date(dx))
      }
      return null;
  });

  chicago.yAxis
      .axisLabel('Price ($/Dth)')
      .tickFormat(function(d) { return '$' + d3.format(',.2f')(d) });

  nv.log(testdata);
  d3.select('#chicago svg')
      .datum(testdata)
      .call(chicago);

  nv.utils.windowResize(chicago.update);

  return chicago;
});

我将如何包装该函数,以便我可以多次重复使用它而不必重复它并为每个图表替换名称(在本例中为“芝加哥”)?

【问题讨论】:

    标签: javascript d3.js nvd3.js


    【解决方案1】:

    这很简单,这是一种方法。

    HTML:

    <div id='chart1'>
        <h3>My Chart 1</h3>
        <svg></svg>
    </div>
    <div id='chart2'>
        <h3>My Chart 2</h3>
        <svg></svg>
    </div>
    <div id='chart3'>
        <h3>My Chart 3</h3>
        <svg></svg>
    </div>
    

    JavaScript:

    // Call my charts , pass in my div id here
    drawChart('chart1');
    drawChart('chart2');
    drawChart('chart3');
    
    //Donut chart example
    function drawChart(div) {
        var width = height = 400;
        
        nv.addGraph(function () {
            var chart = nv.models.pieChart()
                .x(function (d) {
                return d.label
            }).y(function (d) {
                return d.value
            }).width(width)
              .height(height)
              .showLabels(true)
              .labelThreshold(.05)
              .labelType("percent")
              .donut(true);
    
            d3.select("#" + div + " svg")
                .datum(exampleData())
                .attr('width', width).attr('height', height)
                .transition().duration(350)
                .call(chart);
    
            return chart;
        });
    }
    

    这是其中的working version

    【讨论】:

      猜你喜欢
      • 2012-05-09
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 2013-03-21
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 2012-03-05
      相关资源
      最近更新 更多