Google chart redraw/scale on window resize
Asked Answered
B

10

87

How do I redraw/rescale a google linechart on window resize?

Bullnecked answered 21/1, 2012 at 4:51 Comment(1)
this should really be a built in feature of the visualization api!Aceous
C
73

To redraw only when the window resize is completed and avoid multiple triggers, I think is better create an event:

//create trigger to resizeEnd event     
$(window).resize(function() {
    if(this.resizeTO) clearTimeout(this.resizeTO);
    this.resizeTO = setTimeout(function() {
        $(this).trigger('resizeEnd');
    }, 500);
});

//redraw graph when window resize is completed  
$(window).on('resizeEnd', function() {
    drawChart(data);
});
Cocaine answered 4/12, 2013 at 19:26 Comment(0)
P
39

The original code by Google simply does this at the end:

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

Changing it with a little javascript you can scale it when the window resizes:

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

window.onload = resize;
window.onresize = resize;
Payer answered 21/6, 2012 at 22:35 Comment(6)
It might be worth mentioning that when you fetch "data" over ajax , triggering a XHTTPRequest on EVERY window resize 'step' might be a bit stressfull on your server, I think it would be better to somehow cache the results of the ajax request and reuse that data, but your solution works for me! +1Aceous
wasnt working for me, needed to delete old rezults from div before drawing again: $('#chart_div').empty();Adaurd
window.onload = resize(); is equivalent to resize(); window.onload = undefined;Eradis
It works as you describe it when making the window bigger, but if you shrink the window you need to first empty the chart div, as Mantas D pointed out. $('#chart_div').empty(); This will allow the browser to shrink the div, before redrawing the chart.Ree
I like this solution. I don't like timers or recursive functions on client side, why consistently use CPU power?Lidalidah
Comments totally miss the point if you ask me. Is there no way to re-render the chart without re-passing data? The data didn't change, the window size did.Bearer
U
9

Since the window.resize event fires multiple times on each resize event, I believe that the best solution is to use smartresize.js and use smartdraw(). This limits the number of chart redraw’s per window.resize.

By using the provided js you can do it as simply as this:

// Instantiate and draw our user charts, passing in some options (as you probably were doing it)
var chart = new google.visualization.LineChart(document.getElementById('div_chart'));
chart.draw(data, options);

// And then:
$(window).smartresize(function () {
    chart.draw(data, options);
});
Urbain answered 9/7, 2013 at 11:24 Comment(1)
misspell "otions" -> "options"Chloral
T
4

This is the simplest way I can work out of doing this without causing too much stress to the browser:

    var chart1 = "done";

$(window).resize(function() {
if(chart1=="done"){
chart1 = "waiting";
setTimeout(function(){drawChart();chart1 = "done"},1000);
}
});

All it does is wait 1 second before the chart reloads and doesn't let the function call again in this waiting period. as window resize functions are called multiple times any time you change the window size this helps make the function only actually work once each time you change the window size, the rest of the calls get stopped by the if statement.

I hope this helps

Threedimensional answered 13/10, 2013 at 22:43 Comment(1)
Excellent for its simplicity.Numen
U
3

There is no option in Google Visualization API to make Google Charts responsive.

But we can make Google Charts responsive as Window Resizes. To make Google Chart responsive there is jQuery library available at GitHub - jquery-smartresize licensed under MIT License, which has the ability to resize graphs on window resize event.

This project on GitHub has two script files :-

jquery.debouncedresize.js: adds a special event that fires once after the window
has been resized.

&

jquery.throttledresize.js: adds a special event that fires at a reduced rate (no 
more double events from Chrome and Safari).

Here are two examples of responsive charts...

  1. Responsive Google Pie Chart
  2. Responsive Google Bar Chart

We can change the bottom padding of visualization_wrap to match the desired aspect ratio of chart.

Calculate as Height / Width x 100
For a 16x9 display it would be 9/16 = 0.5625 x 100 = 56.25%
For a square it'd be 100%

We can customize chartarea option of Google Chart to ensure that labels don't get cut off on resizing.

Unicuspid answered 4/8, 2014 at 11:29 Comment(0)
E
2

Redraw/rescale a Google linechart on window resize:

$(document).ready(function () {
    $(window).resize(function(){
        drawChart();
    });
});
Extrabold answered 1/4, 2013 at 10:20 Comment(2)
This is really inefficient since you just have to call chart.draw(data, options); again. This will fetch all information and do repetetive and unnecessary work.Urbain
how to force redraw example on click we force to call resize function.Stertorous
A
1

I personally prefer the following approach, if You can live with using addEventListener, and don't mind lack of support for IE < 9.

var windowResizeTimer;
window.addEventListener('resize', function(e){
    clearTimeout(windowResizeTimer);
    windowResizeTimer = setTimeout(function(){
        chart.draw(data, options);
    }, 750);
});

Note the use of the setTimeout() and clearTimeout() functions and the added delay of 750 milliseconds, which makes this slightly less intensive when multiple resize events fire in quick succession (which is often the case for browsers on desktop when resizing using a mouse).

Annmarieannnora answered 28/4, 2016 at 21:24 Comment(0)
U
0

I've been stuck on the same thing for days and I found out that adding an event works best.

window.addEventListener("resize", drawChart);

Just add this line after declaring your function and it will work fine.

Replace drawChart with the name of your function.

Unsaddle answered 7/5, 2020 at 12:18 Comment(0)
B
0

Try with these approaches

window.dispatchEvent(new Event('resize'))
Chartkick.charts["<id of chart element like chart-1>"].redraw()
Boring answered 23/1, 2021 at 13:20 Comment(0)
F
-1

Using Tiago Castro's answer, I have implemented a line chart to show the demonstration.

google.load('visualization', '1', {
  packages: ['corechart', 'line']
});
google.setOnLoadCallback(drawBackgroundColor);

function drawBackgroundColor() {
  var data = new google.visualization.DataTable();
  data.addColumn('number', 'X');
  data.addColumn('number', 'Compute Time');
  data.addColumn('number', 'Compute Times');
  console.log("--");
  data.addRows([
    [0, 0, 0],
    [10, 10, 15],
    [20, 20, 65]
  ]);
  console.log(data);
  var options = {
    height: 350,
    legend: {
      position: 'bottom'
    },
    hAxis: {
      title: 'Nb Curves'
    },
    vAxis: {
      title: 'Time (ms)'
    },
    backgroundColor: '#f1f8e9'
  };

  function resize() {
    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }
  window.onload = resize();
  window.onresize = resize;

}
<script src='https://www.google.com/jsapi'></script>
<div id="chart_div">
Favin answered 18/5, 2016 at 5:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.