简体   繁体   中英

Google Charts Javascript, using two arrays for data input for a line chart

I am trying to create a line chart using the Google Charts package. The problem I have is that I want to plot data from two Javascript arrays. I did find some code showing how to do this for a barchart, but I can not get the same code to work for creating a line chart. This is the code I have so far.

<html>
<head>


  <!--Load the AJAX API-->
  <script type="text/javascript" src="https://www.google.com/jsapi"> </script>
  <script type="text/javascript">
    google.load("visualization", "1", {packages:["corechart"]});
    google.setOnLoadCallback(drawChart);


    var time = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    var suseptible = [0, 4, 5, 2, 6, 7, 3, 9, 9, 9];

    function drawChart(){

        var data = google.visualization.arrayToDataTable();
        data.addColumn('number', 'Time');
        data.addColumn('number', 'Suseptible');

        for(var i=0; i < time.length; i++){
            var row = [time[i], suseptible[i]];
            data.addRow(row);
        }



        var options = {

        };

        var chart = new  google.visualization.LineChart(document.getElementById('chart_id'));
        chart.draw(data, options);
    }


</script>
</head>

<body>
<!--Div that will hold the pie chart-->
<div id="chart_id"></div>
</body>
</html>

Can anyone explain the basics for how to do this. I have been looking in the Google Charts documentation, but I am having a hard time solving this.

First, I would recommend using loader.js instead of jsapi to load the library.
Loading frozen version '44' due to recent issues .

Next, I noticed you are using arrayToDataTable
This requires an array argument be passed (see examples from link).
Use this when your data is already complete and exists in an array.

Next you need a domain column, typically the first column is a date or label for which the value represents. In this example, I use the array index as the "Id".

 // load frozen version 44 google.charts.load('44', { callback: drawChart, packages: ['corechart'] }); // init array data var time = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var suseptible = [0, 4, 5, 2, 6, 7, 3, 9, 9, 9]; function drawChart(){ // create DataTable var data = new google.visualization.DataTable(); data.addColumn('number', 'Id'); data.addColumn('number', 'Time'); data.addColumn('number', 'Suseptible'); // load data for (var i = 0; i < time.length; i++) { var row = [i, time[i], suseptible[i]]; data.addRow(row); } var options = {}; var chart = new google.visualization.LineChart(document.getElementById('chart_id')); chart.draw(data, options); } 
 <script src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_id"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM