如何从CSV文件制作气泡图?

时间:2015-06-07 18:32:51

标签: javascript php csv google-visualization bubble-chart

所以我有以下文件data.csv。看起来像这样:

TestID,Cronbach,Percent Correct,Population
12416,0.866,0.17,26
12421,0.945,0.21,8
12385,0.777,0.40,258
12412,0.85,0.44,34
12407,0.831,0.45,48

我希望它看起来像这样:

[
["Test ID", "Cronbach", "Percent Correct", "Population"],
["12416", 0.866, 0.17, 26],
["12421", 0.945, 0.21, 8],
["12385", 0.777, 0.40, 258],
["12412", 0.85, 0.44, 34],
["12407", 0.831, 0.45, 48]
]

有没有办法在php中制作转换代码,将我的CSV文件转换成上面的格式。我需要这个,因为我想将代码放入Google Bubble Chart

问:我如何制作可以将其转换为可接受格式的代码以适合谷歌气泡图?

1 个答案:

答案 0 :(得分:2)

以下示例演示了如何解析csv文件内容:

function prepareChartData(data) {
    var items = [];
    var lines = data.split(/\r\n|\n/);

    lines.forEach(function(line,i){
         if(line.length > 0){
             var item =  line.split(','); 
             if(i > 0){
                 item[1] = parseFloat(item[1]);
                 item[2] = parseFloat(item[2]);
                 item[3] = parseInt(item[3]);   
             }
             items.push(item);
         }
    });
    return items;
}

<强>结果

[
  [
    "TestID",
    "Cronbach",
    "Percent Correct",
    "Population"
  ],
  [
    "12416",
    0.866,
    0.17,
    26
  ],
  [
    "12421",
    0.945,
    0.21,
    8
  ],
  [
    "12385",
    0.777,
    0.4,
    258
  ],
  [
    "12412",
    0.85,
    0.44,
    34
  ],
  [
    "12407",
    0.831,
    0.45,
    48
  ]
]

完整示例

google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(function(){
    readChartData()
    .then(prepareChartData)
    .done(drawChart);
});

function drawChart(items) {

    var data = google.visualization.arrayToDataTable(items);
    var options = {
        title: 'Chart'
    };
    var chart = new google.visualization.BubbleChart(document.getElementById('chart_div'));
    chart.draw(data, options);
}


function readChartData(complete)
{
    return $.ajax({
        type: "GET",
        url: "data.csv",
        dataType: "text"
    });  
}


function prepareChartData(data) {
    var items = [];
    var lines = data.split(/\r\n|\n/);

    lines.forEach(function(line,i){
         if(line.length > 0){
             var item =  line.split(','); 
             if(i > 0){
                 item[1] = parseFloat(item[1]);
                 item[2] = parseFloat(item[2]);
                 item[3] = parseInt(item[3]);   
             }
             items.push(item);
         }
    });
    return items;
}