簡體   English   中英

如何根據信息表繪制動態折線圖?

[英]How to draw a dynamic line chart based on an infotable?

我想使用 d3.js 基於信息表繪制動態折線圖。 我已將信息表中的信息轉換為兩個 arrays:一維數組xValueArray: [0, 10, 20, 30, 40]和一個二維數組yValueArray: [[0, 20, 30, 40, 50], [0, 200, 250, 400, 450]] 我的邏輯是,我可以獲得一個數據集,其中 xValueArray 映射到 yValueArray 中的 arrays 以表示 x 和 y 坐標。 因此,我使用了 map function 來制作數據集。

    var result = xValueArray.map(function (x, i) { 
        return [x, yValueArray[0][i]];
    });
    console.log(result); //returns [[0,0], [10,20], [20,30], [30,40], [40, 50]]

    var data = result.map(function(d) {
        return {
          x: d[0],
          y: d[1]
        };
    });
    console.log(data); //returns [[x:0, y:0], [x:10, y:20], [x:20, y:30], [x:30, y:40], [x:40, y:50]]

    //************* Plotting of graph ***************   
    var lineFunction = d3.line()
        .x(function(d) {return x(d.x); })
        .y(function(d) {return y(d.y); })
        .curve(d3.curveLinear);

    //plot line
    var path1 = g.append("path")
        .attr("class", "path1")
        .attr("id", "blueLine")
        .attr("d", lineFunction(data))
        .attr("stroke", "blue")
        .attr("stroke-width", 2)
        .attr("fill", "none")
        .attr("clip-path", "url(#clip)");

折線圖將繪制得很好,僅繪制一條線,因為我僅將 yValueArray 中的第一個數組映射到 xValueArray。 但是,我想讓圖表動態,這意味着我希望根據用戶在信息表中輸入的數據字段的數量繪制折線圖。 在這種情況下,數據字段的數量為 2,因為 yValueArray 中有 2 個 arrays。 如果數據字段的數量增加,yValueArray 中的 arrays 的數量也會增加,我必須在折線圖上對應 plot 線。

我應該如何 go 這樣做? 任何幫助是極大的贊賞!

與其使用x數組作為映射y值的基礎,不如反過來:

 const yValueArray = [ [0, 20, 30, 40, 50], [0, 200, 250, 400, 450] ]; const xValueArray = [0, 10, 20, 30, 40]; const data = yValueArray.map(data => data.map((d, i) => ({ x: xValueArray[i], y: d })) ); console.log(data);

這適用於 yValueArray 上有多少內部yValueArray

然后在您的輸入選擇中使用該數據:

 const yValueArray = [ [0, 20, 30, 40, 50], [0, 200, 250, 400, 450] ]; const xValueArray = [0, 10, 20, 30, 40]; const data = yValueArray.map(data => data.map((d, i) => ({ x: xValueArray[i], y: d })) ); const x = d3.scaleLinear(); const y = d3.scaleLinear(); const lineFunction = d3.line().x(function(d) { return x(dx); }).y(function(d) { return y(dy); }).curve(d3.curveLinear); const path1 = d3.select("svg").selectAll(null).data(data).enter().append("path").attr("d", lineFunction).attr("stroke", "blue").attr("stroke-width", 2).attr("fill", "none");
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script> <svg width="300" height="400"></svg>

暫無
暫無

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

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