2017-03-09 81 views
0

我有三個陣列,我從一個XML文件解析中,詳述如下:渲染chart.js之氣泡圖使用數組數據

["x": "23.561799", "x": "-10.713591", "x": "-20.516543", "x": "27.352751", "x": "-21.090982"] 
["y": "-5.777557", "y": "-24.425175", "y": "9.131939", "y": "7.052970", "y": "-26.059631"] 
["r": "10.000000", "r": "10.000000", "r": "10.000000", "r": "10.000000", "r": "10.000000"] 

比方說,這些被稱爲arrayX,arrayY和arrayR。我將如何使用這些在Chart.js中渲染氣泡圖? 我的代碼來創建這裏簡單氣泡圖:

var ctx = document.getElementById("myChart"); 
        var myChart = new Chart(ctx, { 
         type: 'bubble', 
         data: { 
          labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], 
          datasets: [ 
          { 
           label: 'Gaze Map Month 1', 
           data: [ 
           { 
            x: 23, 
            y: -10, 
            r: 10 
           }, 
           { 
            x: -10.713591, 
            y: -24.425175, 
            r: 3 
           }, 
           { 
            x: -20.516543, 
            y: 9.131939, 
            r: 36 
           }, 
           { 
            x: 27.352751, 
            y: 7.052970, 
            r: 19 
           }, 
           { 
            x: -21.090982, 
            y: -26.059631, 
            r: 2 
           } 

           ], 
           backgroundColor:"#FF6384", 
           hoverBackgroundColor: "#FF6384", 
          }] 
         }, 
         options: { 
          scales: { 
           yAxes: [{ 
            ticks: { 
             beginAtZero:true, 
             min: -30, 
             max: 30 
            } 
           }], 
           xAxes: [{ 
            ticks: { 
             beginAtZero:true, 
             min: -30, 
             max: 30 
            } 
           }] 
          } 
         } 
        }); 

注意,陣列的格式可以被改變如果需要的話,以便用於只的值。

回答

1

由於您正在動態獲取數據,只需遍歷數據並以chart.js所需的格式構建一個chartData對象。彙總完數據後,只需在圖表定義中使用該數據。看下面的例子

var xArray = ["x": "23.561799", "x": "-10.713591", "x": "-20.516543", "x": "27.352751", "x": "-21.090982"]; 
var yArray = ["y": "-5.777557", "y": "-24.425175", "y": "9.131939", "y": "7.052970", "y": "-26.059631"]; 
var rArray = ["r": "10.000000", "r": "10.000000", "r": "10.000000", "r": "10.000000", "r": "10.000000"]; 

var chartData = []; 

xArray.forEach(function(e, i) { 
    chartData.push({ 
    x: parseFloat(e), 
    y: parseFloat(yArray[i]), 
    r: parseFloat(rArray[i]), 
    }); 
}); 

var ctx = document.getElementById("myChart"); 
var myChart = new Chart(ctx, { 
    type: 'bubble', 
    data: { 
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], 
    datasets: [ 
     { 
     label: 'Gaze Map Month 1', 
     data: chartData, 
     backgroundColor:"#FF6384", 
     hoverBackgroundColor: "#FF6384", 
     } 
    ] 
    }, 
    options: { 
    scales: { 
     yAxes: [{ 
     ticks: { 
      beginAtZero:true, 
      min: -30, 
      max: 30 
      } 
     }], 
     } 
    } 
    } 
}); 
+0

噢,我是男孩我很無能。感謝您的幫助,這很好! –