2016-07-22 89 views
0

我試圖與d簡單的線圖和角度指令。 svg區域顯示在頁面上,但行部分正在渲染頁面。D3行渲染斷

我使用D3 V4

我做縮放X和Y數據。我的console.log顯示x和y值都應該符合svg的寬度和高度。我一直在研究一段時間,似乎無法找到任何可行的解決方案。

這裏是角碼:

graphics.directive('lineVis', function(){ 
return{ 
    restrict: 'E', 
    scope: { 
     val: '=', 
     grouped: '=' 
    }, 
    link: function(scope, element, attrs){ 
     var margin = 25, 
      width = 960, 
      height = 500; 
      data = [{_id:16998.0, total: 1854},{_id:16999.0, total: 2157},{_id:17000.0, total: 2389},{_id:17001.0, total: 2187},{_id:17002.0, total: 1973},{_id:17003.0, total: 1050}]; 

     console.log(data.length); 
     var x = d3.scaleLinear() 
      .range([margin, width-margin]) 
      .domain(d3.extent(data, function(d) {return d._id;})); 
      //[d3.min(data, function(d){return d._id}), d3.max(data, function(d){return d._id})]) 

     var y = d3.scaleLinear() 
      .range([margin, height-margin]) 
      .domain([0, d3.max(data, function(d){ 
       return d.total; 
      })]); 

     var line = d3.line() 
      .x(function(d){ 
       console.log('Y: '+ y(d.total) + ' X: ' + x(d._id)); 
       return (d._id); 
      }) 
      .y(function(d){ 
       return y(d.total); 
      }) 


     var svg = d3.select(element[0]) 
      .append('svg') 
      .attr('width', width+margin) 
      .attr('height', height+margin); 

     svg.selectAll('*').remove() //remove all previous elements 

     svg.append('path') 
      .attr('class', 'line') 
      .attr('stroke', '#777') 
      .attr('d', line(data)); 
     } 
    } 
}); 

而CSS:

.line { 
     fill: none; 
     stroke: steelblue; 
     stroke-width: 2px; 
    } 

我知道的HTML工作,因爲SVG和線渲染,該行剛剛渲染畫面。

感謝您的幫助!

回答

0

你忘了一個g元素的SVG,轉換爲保證金值附加。看看Mike的例子https://gist.github.com/mbostock/3019563

爲了防止重複代碼,從寬度/高度減去邊緣和限定其結果作爲寬度/高度。現在你不必一直說「 - 保證金」。

//in case you want different values per side 
var margin = {top: 25, right: 25, bottom: 25, left: 25}; 

var width = 960 - margin.left - margin.right, 
    height = 500 - margin.top - margin.bottom; 

var svg = d3.select(element[0]) 
      .append('svg') 
      .attr('width', width+margin) 
      .attr('height', height+margin); 
      .append('g') 
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); 

var x = d3.scale.linear() 
    .range([0, width]); 

var y = d3.scale.linear() 
    .range([height, 0]); 
0

謝謝埃裏克!我同意這使得代碼更易於閱讀和更靈活。 (以及實際添加邊距)

我也離開了X比例上d3.line() 應該是:現在

var line = d3.line() 
     .x(function(d){ 
      console.log('Y: '+ y(d.total) + ' X: ' + x(d._id)); 
      return x(d._id); // <-- added x call 
     }) 
     .y(function(d){ 
      return y(d.total); 
     }) 

線呈現!但是它現在倒...嬰兒學步

編輯:

,當我說倒,我的意思是在右上角的線圖開始

SOLUTION:

開關。域對於y縮放器:

var y = d3.scaleLinear() 
      .range([0, height]) 
      .domain([d3.max(data, function(d){ 
       return d.total; 
      }), 0]); 

希望這可以幫助別人!