简体   繁体   中英

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?

Edit: @WhiteHat answer options.backgroundColor = 'cyan'; works quite well but how can i add an animation like:

  animation: {
            duration: 4000,
            startup: true,
            easing: 'inAndOut',
        }

to an existing option.

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')); google.visualization.events.addOneTimeListener(chart, '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 }); google.visualization.events.addOneTimeListener(wrapper, 'ready', function () { wrapper.setOption('backgroundColor', 'magenta'); wrapper.draw(); }); wrapper.draw(); }, packages: ['corechart'] }); 
 div { padding: 8px; } 
 <script src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div> <div id="wrapper_div"></div> 

This will be my suggestion:

Every time you have a new data. Call  location.reload();

Which will reload the page and then from there load function will be automatically called. Load function are as follows.

$(function(data,options) {

drawCustomChart(data,options);

});

Define a custom function which will take data and redraw the chart. Cutom funciton is as follows:

function drawCustomChart(data,options){
chart.draw(data, {
  width: 400,
  height: 240,
  title: 'Toppings I Like On My Pizza',
  colors: ['#e0440e', '#e6693e', '#ec8f6e', '#f3b49f', '#f6c7b6'],
  is3D: true


});


}


After drawing the chart I thing this is the only thing which will fulfill your requirement. Because somewhere down the line we are consuming google Api to draw the chart. And it does not give liberty to change the option after the chart has been drawn.

Thanks.

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