2017-04-20 182 views
1

我需要創建一個覆蓋圖。我不明白如何實現覆蓋和應該是什麼樣的數據。也許熟悉d3.js並有技巧構建覆蓋圖的人可以解釋如何做到這一點。d3.js覆蓋圖

一個類似的例子: enter image description here

overlayGraph.js

var OverlayGraph = (function() { 

    return { 

     // Initializing the module 
     /* 
      dataFile - the path to the json file 
      selector - place of drawing chart 

     */ 
     init: function(dataFile, selector) { 
      d3.json(dataFile, data => { 
       this.drawOverlayGraph(data, selector); 
      }); 
     }, 

     // Draw out data 
     drawOverlayGraph: (data, selector) => { 
      // === BOILERPLATE === 
      var margin = { top: 20, right: 100, bottom: 30, left: 100 }, 
       width = 960 - margin.left - margin.right, 
       height = 500 - margin.top - margin.bottom; 

      // === SVG Container === 
      var svg = d3.select(selector) 
         .append('svg') 
         .attr('width', width + margin.left + margin.right) 
         .attr('height', height + margin.top + margin.bottom) 
         .append('g') 
         .attr("transform", "translate(" + margin.left + ", " + margin.top + ")"); 

      // === SCALE === 
      var xScale = d3.scale.linear() 
         .domain([0, d3.max(data, d => { 
          return +d.x; 
         })]) 
         .range([0, width]); 

      var yScale = d3.scale.linear() 
         .domain([0, d3.max(data, d => { 
          return +d.y; 
         })]) 
         .range([height, 0]); 

      // === AXES === 
      var xAxis = d3.svg.axis() 
        .scale(xScale) 
        .orient('bottom') 
        .innerTickSize(-height) 
        .outerTickSize(0) 
        .tickPadding(10); 

      var yAxis = d3.svg.axis() 
        .scale(yScale) 
        .orient('left') 
        .innerTickSize(-width) 
        .outerTickSize(0) 
        .tickPadding(10); 

      // === Drawing axes === 
      svg.append('g') 
       .attr('class', 'x axis') 
       .attr("transform", "translate(0," + height + ")") 
       .call(xAxis); 

      svg.append('g') 
       .attr('class', 'y axis') 
       .call(yAxis); 

      // === VIZUALIZATION === 
      var line = d3.svg.line() 
       .interpolate('basis') 
       .x(d => { 
        return xScale(d.x); 
       }) 
       .y(d => { 
        return yScale(d.y); 
       }); 

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

    } 

})(); 

OverlayGraph.init('data.json', 'body'); 

我的數據是這樣的:

[ 
    { 
     "x": "0", 
     "y": "5" 
    }, 
    ... 
] 

問候

回答

0

你想要的是一個區域https://github.com/d3/d3-shape/blob/master/README.md#areas ÿ OU必須找到一種方式來定義的最低值,併爲你排隊的每個點上的區域頂部的值,然後做一個

var area = d3.area() 
    .x(function(d, i) { return x(d.data.date); }) 
    .y0(function(d) { return y(d.bottomValue); }) 
    .y1(function(d) { return y(d.topValue); }); 

    g.append("path") 
     .datum(data) 
     .attr("fill", "steelblue") 
     .attr("d", area); 

看到https://bl.ocks.org/mbostock/3885211

+0

感謝您的諮詢。我在我的json文件中添加了一些字段並使用了您的解決方案。結果證明這是必要的。再次感謝。 – Alexander