I have this google chart on a my website. It's a Scatter chart for now, but I would like the solution for all types of charts. If you load the site with a 700-px-wide window for example, the chart dimensions are not responsive: the chart is too wide. Below is the code I am using.
HTML:
<div id="chart_div"></div>
CSS:
#chart_div {
width:100%;
height:20%;
}
JS:
var options = {
title: 'Weight of pro surfer vs. Volume of his pro model',
hAxis: {title: 'Weight (kg)', minValue: 53, maxValue: 100}, //55
vAxis: {title: 'Volume (l)'}, //, minValue: 20, maxValue: 40}, //20
legend: 'none',
width: '100%',
height: '100%',
colors: ['#000000'],
series: {
1: { color: '#06b4c8' },
},
legend: {position: 'top right', textStyle: {fontSize: 8}},
chartArea: {width: '60%'},
trendlines: { 0: {//type: 'exponential',
visibleInLegend: true,
color: 'grey',
lineWidth: 2,
opacity: 0.2,
labelInLegend: 'Linear trendline\n(Performance)'
}
} // Draw a trendline for data series 0.
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'ready', myReadyHandler());
function myReadyHandler() {
chartDrawn.resolve(); }
Edit: It seems that the div #chart_div
has the right size (the one that I set with css), but the chart inside this div doesn't adapt its size...it stays locked with
See the image:
If you are using Twitter Bootstrap, since v3.2 you can leverage the
embed-responsive
styles:Or if you want 4:3 aspect ratio:
Just don´t set the "width" property on the chart JS. That will set the width automatically on load time.
Some code:
For responsive on load works:
Altough it dosen't work when screen size changes during session.
A more efficient resizing snippet is below and re-usable;
The best solution is to change chart view as window resized:
Since the Visualization API charts are not responsive at all, you have to handle everything on your own. Typically, this means listening for the window "resize" event and redrawing your chart then (setting any dimensions as appropriate):