Google注释表从CSV加载

时间:2019-05-30 05:10:10

标签: javascript csv charts google-visualization

我正在尝试通过使用以下示例从CSV文件加载一些数据来创建Google注释图表:

https://developers.google.com/chart/interactive/docs/gallery/annotationchart

我尝试修改代码(使用我有限的JS知识)以从CSV文件加载,但是没有任何图形。

到目前为止,我的代码:

<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type='text/javascript'>
google.charts.load('current', {'packages':['annotationchart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() 
{
$.get('test.csv', function(csvString) 
{
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
arrayData = arrayData.map(function (row) 
{
return 
[new Date(row[0]),row[1]];
});


var data = google.visualization.arrayToDataTable(arrayData);
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));

var options = {
displayAnnotations: true
};

chart.draw(data, options);
}
}
</script>
</head>

<body>
<div id='chart_div' style='width: 900px; height: 500px;'></div>
</body>
</html>

CSV文件

Date,Value1
2014-01-01,1233
2014- 01-02,1334
2014-01-03,1488
2014-01-04,1888
2014-01-05,2011
2014-01-06,1900
2014-01-07,1768
2014-01-08,2345

2 个答案:

答案 0 :(得分:1)

首先,将jquery和jquery csv添加到您的页面。

 Overall
ArbeitsmarkterfahrungTeilzeit             0.7959690
ArbeitsmarkterfahrungVollzeit             2.0983457
Bildungsgrad                              0.5411927
Branche                                   2.9834760
Bundesland                                1.5196212
DauerUnternehmenszugehörigkeit            2.8076939
Geschlecht                                0.6460660
I((ArbeitsmarkterfahrungTeilzeit^2)/100)  0.9484336
I((ArbeitsmarkterfahrungVollzeit^2)/100)  1.7834424
I((DauerUnternehmenszugehörigkeit^2)/100) 2.4356691
inverseMillsRatioPrunedCtreeGiniUs        1.2874896
Migrationshintergrund                     0.5049873
öffenticherDienst                         1.1612920
Unternehmengroesse                        2.3115065

然后按如下所示替换代码。
查看注释以获取解释...

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
// load google charts
google.charts.load('current', {
  packages: ['annotationchart']
}).then(function () {
  // declare data variable
  var arrayData;

  // get csv data
  $.get('test.csv', function(csvString) {
    // get csv data success, convert to an array, draw chart
    arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
    drawChart(arrayData);
  }).fail(function () {
    // get csv data failed, draw chart with hard-coded data, for example purposes
    arrayData = [
      ['Date','Value1'],
      ['2014-01-01',1233],
      ['2014-01-02',1334],
      ['2014-01-03',1488],
      ['2014-01-04',1888],
      ['2014-01-05',2011],
      ['2014-01-06',1900],
      ['2014-01-07',1768],
      ['2014-01-08',2345],
    ];
    drawChart(arrayData);
  });
});

// draw chart
function drawChart(arrayData) {
  // convert string in first column to a date
  arrayData = arrayData.map(function (row) {
    return [new Date(row[0]),row[1]];
  });

  // create google data table, chart, and options
  var data = google.visualization.arrayToDataTable(arrayData);
  var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
  var options = {
    displayAnnotations: true
  };

  // draw chart
  chart.draw(data, options);
}

注意:您可以删除<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script> <script src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div>回调,这是出于示例目的,此处用于堆栈溢出...

答案 1 :(得分:0)

您需要按照以下3个步骤进行操作

  1. 触发ajax请求并获取CSV数据
  2. 将csv数据转换为数组
  3. 在Google图形中传递csv数组

请参考以下示例:

<html>
<head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type='text/javascript'>

        //Step 1: Get string from csv
        $(document).ready(function () {
            $.ajax({
                type: "GET",
                url: "test.csv",
                dataType: "text",
                success: function (data) {
                    //Step 2: Convert "," seprated string into array
                    let arrData = csvToArray(data);
                    //Step 3: call chart with array data
                    callChart(arrData);
                }
            });
        });

        //convert csv string into array function
        function csvToArray(allText) {
            var allTextLines = allText.split(/\r\n|\n/);
            var headers = allTextLines[0].split(',');
            var lines = [];

            for (var i = 1;i < allTextLines.length;i++) {
                var data = allTextLines[i].split(',');
                if (data.length == headers.length) {

                    var tarr = [];
                    for (var j = 0;j < headers.length;j++) {
                        tarr.push(headers[j] + ":" + data[j]);
                    }
                    lines.push(tarr);
                }
            }
            return lines;
        }

        function callChart(arrData) {
            google.charts.load('current', { 'packages': ['annotationchart'] });
            google.charts.setOnLoadCallback(function () { drawChart(arrData); });
        }

        function drawChart(arrData) {
            var data = new google.visualization.DataTable();
            //Step 4: add csv your column
            data.addColumn('date', 'Date');
            data.addColumn('number', 'Kepler-22b mission');
            //Step 5: pass your csv data as array
            data.addRows(arrData);
            var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
            var options = {
                displayAnnotations: true
            };
            chart.draw(data, options);
        }
    </script>
</head>
<body>
    <div id='chart_div' style='width: 900px; height: 500px;'></div>
</body>
</html>