Re: Multiple interactive charts in same page

1,134 views
Skip to first unread message

asgallant

unread,
Sep 5, 2012, 8:06:07 PM9/5/12
to google-visua...@googlegroups.com
You have two functions called "drawChart" - rename them something else (like drawChart1 and drawChart2, or whatever suits you).  In each, check the id's for the filters, charts, and dashboards.  Every element must have its own unique id (and an HTML div with the same id to put the element in), so change the id's so that the different charts and controls end up in different divs.  Then create a third function that calls the two drawing functions, and change the google.setOnLoadCallback() line to reference this function instead of the drawChart function.

Alternatively, you could move all of the code into one function and draw multiple charts from there (you would still need to change the element id's).

As an aside, there is a newer version of the code you copied here.

On Wednesday, September 5, 2012 7:00:13 PM UTC-4, vishnuuvm wrote:
Hi

I am very new to google charts API and have been playing around with available tools and adapting code to suit my requirement.

I have a condition where I need to create two interactive charts on the same page. Mind you I found this code and have simply used it to my needs.
However, when I create two copies of the same code so that I have two charts on the same page, it does not show.
Could someone help me on how to create two interactive charts in the same page

i am posting the code as follows
Thanks


  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

  <script type="text/javascript" src="http://www.google.com/jsapi"></script>

  <script type="text/javascript">

  google.load('visualization', '1.1', {packages: ['controls','corechart']});

  </script>

  <script type="text/javascript">

    

   

  google.setOnLoadCallback(drawChart);

   

  function drawChart() {

  var data = google.visualization.arrayToDataTable([           

              ['x', 'DDD', 'AAA', 'BBB'],

              ['2011',   0.013,   0.035,   0.035],

              ['2012',   0.024,   0.047,   0.0646],

              ['2013',   0.026,   0.077,   0.0977],

              ['2014',   0.037,   0.151,   0.4511],

              ['2015',   0.049,   0.155,   0.5615],

              ['2016',   0.150,   0.261,   0.8724],

              ['2017',   0.611,   0.248,   0.934],

              ['2018',   0.713,   0.337,   0.9945]

    

        

  ]);          

   

  var columnsTable = new google.visualization.DataTable();

  columnsTable.addColumn('number', 'colIndex');

  columnsTable.addColumn('string', 'colLabel');

  var initState = {

  selectedValues: ['AAA']

  };

  // put the columns into this data table (skip column 0)

  for (var i = 1; i < data.getNumberOfColumns(); i++) {

  columnsTable.addRow([i, data.getColumnLabel(i)]);

  initState.selectedValues.push(data.getColumnLabel(i));

  }

   

  var chart = new google.visualization.ChartWrapper({

  chartType: 'LineChart',

  containerId: 'chart_div',

  dataTable: data,

  options: {

  title: 'Total Market',

  width: 700,

  height: 470,

  legend: 'bottom',

  vAxis: {format:'#%'},

  

          animation:{

          duration: 1000,

          easing: 'out',

        }

  }

  });

   

  chart.draw();

   

  var dash = new google.visualization.Dashboard(document.getElementById('dash'));

   

  var columnFilter = new google.visualization.ControlWrapper({

  controlType: 'CategoryFilter',

  containerId: 'colFilter_div',

  options: {

  filterColumnLabel: 'colLabel',

  ui: {

  label: 'Choose a Scenario',

  allowTyping: true,

  allowMultiple: true,

  selectedValuesLayout: 'belowStacked'

  }

  },

  state: initState

  });

   

  var junkChart = new google.visualization.ChartWrapper({

  chartType: 'Table',

  containerId: 'junk_div'

  });

   

  google.visualization.events.addListener(columnFilter, 'statechange', function() {

  var state = columnFilter.getState();

  var row;

  var columnIndices = [0];

  for (var i = 0; i < state.selectedValues.length; i++) {

  row = columnsTable.getFilteredRows([{

  column: 1,

  value: state.selectedValues[i]}])[0];

  columnIndices.push(columnsTable.getValue(row, 0));

  }

  // sort the indices into their original order

  columnIndices.sort(function(a, b) {

  return (a - b);

  });

  chart.setView({

  columns: columnIndices

  });

  chart.draw();

  });

   

  // bind controls to junk chart and draw dash

  dash.bind([columnFilter], [junkChart]);

  dash.draw(columnsTable);

  }

   

   </script>

   </head>

   

  <body style="font-family: Arial;border: 0 none;">

   

  <div id="dash">

  <table>

  <tr style='vertical-align: top'>

  <td style='width: 16px; font-size: 0.9em;'>

  <div id="colFilter_div"></div>

  </td>

  <td style='width: 60px'>

  <div style="float: left;" id="chart_div"></div>

  </td>

  </tr>

  </table>

  </div>

  <div id="junk_div" style="display: none;"></div>

  </body>

  </html>



    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head>

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <script type="text/javascript" src="http://www.google.com/jsapi"></script>

    <script type="text/javascript">

    google.load('visualization', '1.1', {packages: ['controls','corechart']});

    </script>

    <script type="text/javascript">

      

     

    google.setOnLoadCallback(drawChart);

     

    function drawChart() {

    var data = google.visualization.arrayToDataTable([           

                ['x', 'RRR', 'PPP', 'WWW'],

              ['2011',   4176,   4176,  5176],

              ['2012',   6018,   6018,  60018],

              ['2013',   9277,   12100, 92100],

              ['2014',   15681,  78126, 78126],

              ['2015',   17546,  41016, 41016],

              ['2016',   15164,  43623, 29873],

              ['2017',   26334,  54329, 32426],

              ['2018',   26959,  61806, 3980]

       

          

    ]);          

     

    var columnsTable = new google.visualization.DataTable();

    columnsTable.addColumn('number', 'colIndex');

    columnsTable.addColumn('string', 'colLabel');

    var initState = {

    selectedValues: ['PPP']

    };

    // put the columns into this data table (skip column 0)

    for (var i = 1; i < data.getNumberOfColumns(); i++) {

    columnsTable.addRow([i, data.getColumnLabel(i)]);

    initState.selectedValues.push(data.getColumnLabel(i));

    }

     

    var chart = new google.visualization.ChartWrapper({

    chartType: 'LineChart',

    containerId: 'chart_div',

    dataTable: data,

    options: {

    title: 'Total Market ',

    width: 700,

    height: 470,

    legend: 'bottom',

    vAxis: {format:'###,###'},

    

            animation:{

            duration: 1000,

            easing: 'out',

          }

    }

    });

     

    chart.draw();

     

    var dash = new google.visualization.Dashboard(document.getElementById('dash'));

     

    var columnFilter = new google.visualization.ControlWrapper({

    controlType: 'CategoryFilter',

    containerId: 'colFilter_div',

    options: {

    filterColumnLabel: 'colLabel',

    ui: {

    label: 'Choose a Scenario',

    allowTyping: true,

    allowMultiple: true,

    selectedValuesLayout: 'belowStacked'

    }

    },

    state: initState

    });

     

    var junkChart = new google.visualization.ChartWrapper({

    chartType: 'Table',

    containerId: 'junk_div'

    });

     

    google.visualization.events.addListener(columnFilter, 'statechange', function() {

    var state = columnFilter.getState();

    var row;

    var columnIndices = [0];

    for (var i = 0; i < state.selectedValues.length; i++) {

    row = columnsTable.getFilteredRows([{

    column: 1,

    value: state.selectedValues[i]}])[0];

    columnIndices.push(columnsTable.getValue(row, 0));

    }

    // sort the indices into their original order

    columnIndices.sort(function(a, b) {

    return (a - b);

    });

    chart.setView({

    columns: columnIndices

    });

    chart.draw();

    });

     

    // bind controls to junk chart and draw dash

    dash.bind([columnFilter], [junkChart]);

    dash.draw(columnsTable);

    }

     

     </script>


Diana Flores

unread,
Sep 8, 2012, 8:34:13 PM9/8/12
to google-visua...@googlegroups.com
Hi asgallant!!!!, you help me again!!!, i did the second option you suggest, it works!!!, its very important to add the div id at the end!!!

function drawChart() {

// data for the first chart!!!
           var jsonData =$.ajax({
          .................
          }).responseText;
    
        var data = new google.visualization.DataTable(.....);
        var options = {.....};
        var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
       
// data for the second
       
        var data2 = google.visualization.arrayToDataTable(......);

        var options2 = {.....};

        var chart2 = new google.visualization.LineChart(document.getElementById('chart_div2'));
       
// draw 2 charts!!!
        chart2.draw(data2, options2);
        chart.draw(data,options);

      }

</script>
  </head>
  <body>
    <div id="chart_div" ></div>
    <div id="chart_div2" ></div>
  </body>
</html>

But just one thing, how can i put the chart to the right? so they could be next to each other?

asgallant

unread,
Sep 9, 2012, 12:39:03 AM9/9/12
to google-visua...@googlegroups.com
Use CSS to position the divs:

#chart_div {
    floatleft
}
#chart_div2 {
    floatright
}
.clear {
    clearboth;
    displaynone;
} 

When floating HTML elements, you should also add something to clear the float effect after the floated elements; otherwise your HTML elements might not line up the way you want:

<div id="chart_div"></div>
<div id="chart_div2"></div>
<div class="clear"></div> 

Keep the "clear" div empty (as it won't be visible on the page).

Diana Flores

unread,
Sep 9, 2012, 1:13:50 AM9/9/12
to google-visua...@googlegroups.com
HI!!, where should i put this:

Diana Flores

unread,
Sep 9, 2012, 1:18:06 AM9/9/12
to google-visua...@googlegroups.com
<style type="text/css">
#chart_div {
    floatleft
}
#chart_div2 {
    floatright
}
.clear {
    clearboth;
    displaynone;
} 

 </style> ?????????
 

Daniel LaLiberte

unread,
Sep 9, 2012, 9:31:27 AM9/9/12
to google-visua...@googlegroups.com
An inline style element should work, or you can put it in a separate CSS file that you load.


--
You received this message because you are subscribed to the Google Groups "Google Visualization API" group.
To view this discussion on the web visit https://groups.google.com/d/msg/google-visualization-api/-/Y6RASMbT-QkJ.

To post to this group, send email to google-visua...@googlegroups.com.
To unsubscribe from this group, send email to google-visualizati...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/google-visualization-api?hl=en.



--
dlaliberte@Google.com   562D 5CC, Cambridge MA
daniel.laliberte@GMail.com 9 Juniper Ridge Road, Acton MA

asgallant

unread,
Sep 9, 2012, 10:02:44 PM9/9/12
to google-visua...@googlegroups.com
You may also need to add "display: inline-block;" to the chart div's CSS.

The CSS can be put in the <head> of the HTML page or in a separate CSS file.


On Sunday, September 9, 2012 9:31:33 AM UTC-4, Daniel LaLiberte wrote:
An inline style element should work, or you can put it in a separate CSS file that you load.
On Sun, Sep 9, 2012 at 1:18 AM, Diana Flores <dian...@gmail.com> wrote:
<style type="text/css">
#chart_div {
    floatleft
}
#chart_div2 {
    floatright
}
.clear {
    clearboth;
    displaynone;
} 

 </style> ?????????
 

--
You received this message because you are subscribed to the Google Groups "Google Visualization API" group.
To view this discussion on the web visit https://groups.google.com/d/msg/google-visualization-api/-/Y6RASMbT-QkJ.

To post to this group, send email to google-visua...@googlegroups.com.
To unsubscribe from this group, send email to google-visualization-api+unsub...@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/google-visualization-api?hl=en.
dlali...@Google.com   562D 5CC, Cambridge MA
daniel.l...@GMail.com 9 Juniper Ridge Road, Acton MA

Diana Flores

unread,
Sep 11, 2012, 11:27:28 PM9/11/12
to google-visua...@googlegroups.com
Hi, sorry to reply until now, i was busy!!!...i dont know if im using it rigth!!

it shows this error:

Fecha y hora: 11/09/2012 09:23:59 p.m.
Error: SyntaxError: missing } in XML expression
Archivo de origen: http://localhost/MyProject/Tigo/graf/goochart2.html
Línea: 76, columna: 9
Código fuente:
    float: left;

this is how i put it:

        var chart3 = new google.visualization.LineChart(document.getElementById('chart_div3'));
       
        chart3.draw(data3, options3);

     
       
      }

<style type="text/css">
#chart_div {
    float: left;
}
#chart_div2 {
    float: right;
}
#chart_div3 {
    float: center;

}
​.clear {
    clear: both;
    display: none;
}​
 </style>
           
    </script>
  </head>
  <body>

    <div id="chart_div" display: inline-block; ></div>
    <div id="chart_div2" display: inline-block;></div>
    <div id="chart_div3" display: inline-block;></div>
    <div class="clear"></div>
  </body>
</html>

Diana Flores

unread,
Sep 12, 2012, 12:12:21 AM9/12/12
to google-visua...@googlegroups.com
Asgallant, do you know a way to import the data from mysql to an excel. Im using:

header('Content-type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=registrores.xls");
header("Pragma: no-cache");
header("Expires: 0");

etc etc etc...

but it alway pop ups a warning, but it shows me all the data. I dont have problem with this, but it seems its not the better way but the easiest. Have you ever used a lib?PHPExcel?

asgallant

unread,
Sep 12, 2012, 11:40:15 AM9/12/12
to google-visua...@googlegroups.com
The style tag can't be inside the script tag, just move it outside the script and it should be fine.

asgallant

unread,
Sep 12, 2012, 11:44:50 AM9/12/12
to google-visua...@googlegroups.com
I believe there are libraries for doing that, but the best way to do it is to output the data as a csv file.  PHP has a function fputcsv, which outputs an array as a csv file, which excel can read.

Diana Flores

unread,
Sep 13, 2012, 10:05:51 PM9/13/12
to google-visua...@googlegroups.com
This are some of the errors that i get!!!...thanks for the lib im checking it now!!!.

Fecha y hora: 13/09/2012 08:02:55 p.m.
Advertencia: Error al interpretar el valor para 'float'.  Declaración rechazada.Línea: 87

Fecha y hora: 13/09/2012 08:02:55 p.m.
Advertencia: Fin de archivo inesperado mientras se buscaba ',' o '{'.  Juego de reglas ignoradas debido a un mal selector.Línea: 92


Fecha y hora: 13/09/2012 08:04:25 p.m.
Advertencia: Se esperaba el final del valor pero se encontró 'display'.  Error al interpretar el valor para 'clear'.  Declaración rechazada.Línea: 90

Diana Flores

unread,
Sep 13, 2012, 10:24:58 PM9/13/12
to google-visua...@googlegroups.com
Sorry my mistake!!! it works.............!!!!!!!!! A SUPER Thanks!!!
final2.jpg

asgallant

unread,
Sep 14, 2012, 1:14:17 AM9/14/12
to google-visua...@googlegroups.com
You're welcome.
Reply all
Reply to author
Forward
0 new messages