2014-06-16 1 views
1

현재 웹 사이트에서 NVD3를 사용하여 6 개의 차트가있는 페이지 중 하나가있는 차트를 그래프로 표시합니다. 나는 현재 6 개의 그래프 각각에 대해 6 개의 함수를 추가했지만 이것이 문제를 접근하는 가장 우아한 방법이 아니라고 생각합니다. 아래는 관련 HTML의 예입니다/자바 스크립트 코드 : 나는 그것을 반복에 대한 (이 경우 '시카고'에서) 이름을 교체해야하지 않고 그래서 그것을 여러 번 재사용 할 수있는 기능을 포장 할 방법페이지에 여러 개의 NVD3 차트가 있습니다. 자바 스크립트 코드와 랩핑 함수를 단순화하는 방법은 무엇입니까?

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

모든 그래프?

답변

6

매우 간단합니다.이 방법 중 하나입니다.

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> 

자바 스크립트 : 여기

// 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입니다.

희망이 있습니다.