Sizing Google charts to fill div width and height
This CodePen shows an example of making Google Charts responsive. Specifically, the charts are redrawn on resize
:
$(window).resize(function(){
drawChart1();
drawChart2();
});
in addition to setting the width
option,
set chartArea.width
to ensure the chart utilizes the available space
also, when the window is resized, the chart needs to be redrawn
see following working snippet...
google.charts.load('current', {
callback: function () {
drawChart();
$(window).resize(drawChart);
},
packages:['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['x', 'y'],
[0, 0],
[1, 1],
[2, 3],
[3, 7],
[4, 15],
[5, 31]
]);
var options = {
chartArea: {
// leave room for y-axis labels
width: '94%'
},
legend: {
position: 'top'
},
width: '100%'
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.LineChart(container);
chart.draw(data, options);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EDIT
among others, chartArea
also has a property for left
instead of using chartArea.width: '94%'
try setting an absolute left
see following working snippet...
google.charts.load('current', {
callback: function () {
drawChart();
$(window).resize(drawChart);
},
packages:['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['x', 'y'],
[0, 0],
[1, 1],
[2, 3],
[3, 7],
[4, 15],
[5, 31]
]);
var options = {
chartArea: {
left: 40,
width: '100%'
},
legend: {
position: 'top'
},
width: '100%'
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.LineChart(container);
chart.draw(data, options);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>