可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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:
回答1:
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):
function resize () {
// change dimensions if necessary
chart.draw(data, options);
}
if (window.addEventListener) {
window.addEventListener('resize', resize);
}
else {
window.attachEvent('onresize', resize);
}
回答2:
For me, none of the above worked or they were too complex for me to give it a try.
The solution I found is simple and works perfectly. It involves just building a normal Google Chart, in my case a donut chart and then styling it using CSS.
@media screen and (max-width: 1080px) {
div#donutchart {
zoom:0.6;
margin-left:-16%;
}
}
That's all. Of course you can set other values for max-width, zoom and margins to have your chart fit perfectly. My chart is 800x600 (you can see it here).
回答3:
put width 100% of the chart and call the resize function as below
$(window).resize(function(){
yourCallingChartFunction();
});
回答4:
For responsive on load works:
#chart_div {
width:inherit;
height:inherit;
}
Altough it dosen't work when screen size changes during session.
回答5:
If you are using Twitter Bootstrap, since v3.2 you can leverage the embed-responsive
styles:
<div class="embed-responsive embed-responsive-16by9">
<div id="chart_div" class="embed-responsive-item"></div>
</div>
Or if you want 4:3 aspect ratio:
<div class="embed-responsive embed-responsive-4by3">
<div id="chart_div" class="embed-responsive-item"></div>
</div>
回答6:
A more efficient resizing snippet is below and re-usable;
//bind a resizing function to the window
$(window).resize(function() {
if(this.resizeTO) clearTimeout(this.resizeTO);
this.resizeTO = setTimeout(function() {
$(this).trigger('resizeEnd');
}, 500);
});
//usage of resizeEnd
$(window).bind('resizeEnd', function() {
DoSomething();
});
回答7:
The best solution is to change chart view as window resized:
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Value');
data.addColumn('number', 'Sites');
data.addColumn({type: 'string', role: 'tooltip'});
data.addColumn({type: 'string', role: 'style'});
data.addRows([
['valueA', 57, 'Value A is 57', 'stroke-color: #000; stroke-width: 1'],
['valueB', 19, 'Value B is 19', 'stroke-color: #000; stroke-width: 1'],
['valueC', 25, 'Value C is 25', 'stroke-color: #000; stroke-width: 1']
]);
var options = {
colors: ['#fff2af'],
hAxis: {textPosition: 'none',textStyle:{color:'#fff'}},
vAxis: {gridlines: {color: '#fff'},textStyle:{color:'#fff'}},
legend: {position: 'none'},
backgroundColor: '#aadaff'
};
var chart = new google.visualization.ColumnChart(document.querySelector('#chart_div'));
chart.draw(data, options);
$(window).resize(function(){
var view = new google.visualization.DataView(data);
chart.draw(view, options);
})
}
回答8:
Just don´t set the "width" property on the chart JS. That will set the width automatically on load time.
Some code:
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// Set chart options
var options = {
title: "Density of Precious Metals, in g/cm^3",
height: 400
//width: 1100, <--- DON'T SET THIS OPTION, it will be set automatically depending on the size of the container div
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<!--Div that will hold the pie chart-->
<div id="chart_div" class="mt-3" style="height: 400px; width: 100%; border: 1px solid #CCCCCC"></div>
回答9:
I found this Code pen example usefull:
Code pen example of Google Charts Responsive
They do redraw the graph on window resize using jQuery:
$(window).resize(function(){
yourCartdrawChartfuntion();
});