2013-03-20 85 views
1

我剛接觸到highcharts和JS,並試圖繪製來自csv文件(data3.csv)的數據。HighCharts從CSV基本示例中讀取

這裏是目前的代碼:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
     <title>Highcharts Example</title> 


     <!-- 1. Add these JavaScript inclusions in the head of your page --> 
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
     <script type="text/javascript" src="highcharts.js"></script> 
     <!--[if IE]> 
      <script type="text/javascript" src="../js/excanvas.compiled.js"></script> 
     <![endif]--> 


     <!-- 2. Add the JavaScript to initialize the chart on document ready --> 
     <script type="text/javascript"> 
     $(document).ready(function() { 


      var options = { 
       chart: { 
        renderTo: 'container', 
        defaultSeriesType: 'line' 
       }, 
       title: { 
        text: 'Stock Chart' 
       }, 
       xAxis: { 
        categories: [] 
       }, 
       yAxis: { 
        title: { 
         text: 'Price' 
        } 
       }, 
       series: [] 
      }; 

      $.get('data3.csv', function(data) { 

       $.each(lines, function(lineNo, line) { 
       var items = line.split(','); 

       var series = { 
        data: [] 
       }; 

       $.each(items, function(itemNo, item) { 
        if (itemNo == 0) { 
         series.name = item; 
        } else { 
         series.data.push(parseFloat(item)); 
        } 
       }); 

       options.series.push(series); 

       }); 

       var chart = new Highcharts.Chart(options); 
      }); 
     }); 

     </script> 

    </head> 
    <body> 

     <!-- 3. Add the container --> 
     <div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div> 


    </body> 
</html> 

以及CSV文件的內容是:

Date Open 
29/01/2010 538.49 
28/01/2010 544.49 
27/01/2010 541.27 
26/01/2010 537.97 
25/01/2010 546.59 

然而,這是不是給一個圖表(只是給出標題)。

任何人都可以建議我去哪裏錯了嗎?

感謝

+1

首先,這不是一個CSV(逗號分隔值)文件。 – Blaise 2015-01-08 14:53:22

回答

1

在行

var items = line.split(','); 

你應該用逗號樣條CSV,但你有空間。因此,您可以將此行替換爲:

var items = line.split(' '); 

或生成csv哪些項目將以逗號分隔。

結果解析器應該看起來像:

$.get('data.csv', function(data) { 
    // Split the lines 
    var lines = data.split('\n'); 
    // Iterate over the lines and add categories or series 
    $.each(lines, function(lineNo, line) { 
     var items = line.split(','); 
     if(lineNo>0) 
     { 
      options.xAxis.categories.push(items[0]); //set first column from CSV as categorie 
      options.series[0].data.push(parseFloat(items[1])); //set second column from CSV as point value 
     } 

    }); 

    // Create the chart 
    var chart = new Highcharts.Chart(options); 
});