Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array to google charts

I'm trying to pass an array of numbers to a google charts, that array is being pulled by this code from a div with a class .likescount

var i, $mvar = $('.likescount'); // using the $ prefix to use the "jQuery wrapped var" convention

function logit( string )
{
    var text = document.createTextNode( string );
    $('.alllikesinrow').append(text);
    $('.alllikesinrow').append("<br>");
}

logit($mvar.length);

for (i=0; i<$mvar.length; i++)    {
    logit($mvar.eq(i).html());
}

The array is working because im using the append to print it and its working, the hard part is to pass that data to data.addRows, heres the full code i'm using, worked around it, but never got it worked, i'm following this guy that got it working how to add data in google charts using javascript ? , but without luck, any help wold be great.

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


function drawChart() {

    var i, $mvar = $('.likescount'); // using the $ prefix to use the "jQuery wrapped var" convention

    x = [];

    for (i=0; i<$mvar.length; i++ )    {

        x.push( ['1', parseFloat($($mvar[i]).text())] );
    }


  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Day');
  data.addColumn('number', 'Likes');

  data.addRows(x);

  var options = {
    chart: {
      title: 'Likes vs Comentarios',
      subtitle: 'Data Magnus by Optimum'
    },

    height: 500
  };

  var chart = new google.charts.Line(document.getElementById('curve_chart'));

  chart.draw(data, google.charts.Line.convertOptions(options), {pointSize: 1});
}
</script>

Thanks Rodrigo

EDIT: Edited with a working push thanks to WhiteHat

like image 454
Rodrigo Zuluaga Avatar asked Oct 30 '22 03:10

Rodrigo Zuluaga


2 Answers

addRows takes an array of arrays, which is what you are building here...

x = [];

for (i=0; i<$mvar.length; i++)    {
    logit($mvar.eq(i).html());
    x.push( ['August', $mvar[i]] );
}

as such, simply use x for addRows...

var data = new google.visualization.DataTable();
data.addColumn('string', 'Day');
data.addColumn('number', 'Likes');

data.addRows(x);

EDIT

not sure what $('.likescount') contains,
but if each is an element with a number, then try...

x.push( ['August', parseFloat($($mvar[i]).text())] );
like image 119
WhiteHat Avatar answered Nov 11 '22 15:11

WhiteHat


try using google.visualization.arrayToDataTable(array)

the array contains an array of the row values to be displayed in the chart

like image 23
justelouise Avatar answered Nov 11 '22 15:11

justelouise