簡體   English   中英

在D3區域圖中繪制線

[英]Plot lines in D3 Area Chart

我正在使用d3 js庫創建面積圖。

然而,已經實現了在不使用線條的情況下繪制面積圖的情況,需要輸入有關如何繪制線條以分隔區域的信息。

我能想到的一種方法是使用以下方法一一畫線,其中x1 = x2,y1 = 0和y2 = xy繪制點

svg.append("line")
            .data(data)
        .style("stroke", "#e6e3e3")
        .attr("x1", 30)
        .attr("y1", 0)
        .attr("x2", 30)
        .attr("y2", 40);

需要以下幾點幫助。 1.如果有一種方法可以一次性繪制線條(使用功能)。 2.如果分別繪制線(如上所述),則在給定以下數據集的情況下如何計算X和Y軸。

var data = [
    {"quarter": "A", "totalIncome": 60 },
    {"quarter": "B", "totalIncome": 70 },
    {"quarter": "C", "totalIncome": 60 },
    {"quarter": "D", "totalIncome": 80 },
    {"quarter": "E", "totalIncome": 75 }
];

我會做這樣的事情:

如果您有指向頂部的路徑,例如:

var points = { x:0,y:60},{x:50,y:70},{x:100,y:60}.. and so on

您將獲得像垂直線問題一樣的數據。 我將為要創建的5行創建一個新數組,如下所示:

var newLineData = [];
for(i=0;i<data.length;i++){
var thisLine = { x1:i*step,y1:0, x2:i*step,y2:data[i].totalIncome };

newLineData.push(thisLine); //line data

}

然后使用此數據創建如下行:

var link = svg.selectAll(".link")
      .data([newLineData])
    .enter().append("line")
      .attr("class", "link")
      .style('stroke','black')
      .style("stroke-width", function(d) { return Math.sqrt(d.value); });
  //console.log(line);

  link.attr("x1", function(d) { console.log(d); return d.x1; })
        .attr("y1", function(d) { return d.y1; }) 
        //.attr("y1", function(d) { return x[d.y1]; }) if using axis : x is the axis
        .attr("x2", function(d) { return d.x2; })
        .attr("y2", function(d) { return d.y2; });

這是一個無用的提琴技巧: https : //jsfiddle.net/reko91/knetxt5n/

但是,如果您像上面顯示的那樣通過軸,則應該朝您的正確方向走:)

如果JSFiddle發生故障,下面的代碼也是如此。

 var svg = d3.select('#container').append('svg') .attr('width', 500) .attr('height', 500) //.append('g') var data = [ {"quarter": "A", "totalIncome": 60 }, {"quarter": "B", "totalIncome": 70 }, {"quarter": "C", "totalIncome": 60 }, {"quarter": "D", "totalIncome": 80 }, {"quarter": "E", "totalIncome": 75 } ]; var newLineData = []; var step = 50; for(i=1;i<data.length+1;i++){ var thisLine = { x1:i*step,y1:0, x2:i*step,y2:data[i-1].totalIncome }; newLineData.push(thisLine); //line data } var link = svg.selectAll(".link") .data(newLineData) .enter().append("line") .attr("class", "link") .style('stroke','black') .style("stroke-width", function(d) { return Math.sqrt(d.value); }); //console.log(line); link.attr("x1", function(d) { console.log(d); return d.x1; }) .attr("y1", function(d) { return d.y1; }) .attr("x2", function(d) { return d.x2; }) .attr("y2", function(d) { return d.y2; }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> <div id='container'> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM