TheDoctor TheDoctor - 1 year ago 67
Javascript Question

Google charts add option programmatically

Is it possible to add an option to the chart after it is drown?

I know i can delete an option with

delete option.optionname
but how can i add a new one?

Thanks in advance.

Answer Source

anytime you want to change an option, the chart must be redrawn

so it's easy as...

  options.backgroundColor = 'cyan';
  chart.draw(data, options);

you can also use the Chart Wrapper Class, which has a method setOption

but again, it must be redrawn afterwards

see following working snippet, which draws both...

google.charts.load('current', {
  callback: function () {
    var data = google.visualization.arrayToDataTable([
      ['Year', 'Sales', 'Expenses'],
      ['2004',  1000,      400],
      ['2005',  1170,      460],
      ['2006',  660,       1120],
      ['2007',  1030,      540]

    var options = {
      title: 'Company Performance',
      curveType: 'function',
      legend: {position: 'bottom'}

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));, 'ready', function () {
      options.backgroundColor = 'cyan';
      chart.draw(data, options);
    chart.draw(data, options);

    var wrapper = new google.visualization.ChartWrapper({
      chartType: 'LineChart',
      containerId: 'wrapper_div',
      dataTable: data,
      options: options
    });, 'ready', function () {
      wrapper.setOption('backgroundColor', 'magenta');
  packages: ['corechart']
div {
  padding: 8px;
<script src=""></script>
<div id="chart_div"></div>
<div id="wrapper_div"></div>