Setting Google Charts width on load time

2019-02-16 13:59发布

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: enter image description here

9条回答
手持菜刀,她持情操
2楼-- · 2019-02-16 14:36

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>
查看更多
乱世女痞
3楼-- · 2019-02-16 14:36

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>

查看更多
我命由我不由天
4楼-- · 2019-02-16 14:44

For responsive on load works:

#chart_div {
width:inherit;
height:inherit;
}

Altough it dosen't work when screen size changes during session.

查看更多
等我变得足够好
5楼-- · 2019-02-16 14:47

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();
});
查看更多
你好瞎i
6楼-- · 2019-02-16 14:50

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);
})
}
查看更多
时光不老,我们不散
7楼-- · 2019-02-16 14:51

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);
}
查看更多
登录 后发表回答