Setting Google Charts width on load time
Asked Answered
P

10

12

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

Poriferous answered 27/8, 2014 at 9:17 Comment(1)
You should edit the question to specify that you are asking about setting the width on load time, not about responsive charts.Sparrow
P
16

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);
}
Plan answered 28/8, 2014 at 0:52 Comment(7)
thanks for your answer, but for now I am not event thinking about adapting the chart size when resizing the windown, but just making it right when the site loads...to get its dimensions right when the page loads. Resigin the windows will be the next step. Do you understand ?Poriferous
If you set the dimensions of the container div in CSS as percents, then the size of the chart will be set dynamically based on the the size of its container.Plan
that's what I thought and that's exactly what I am doing already: I have updated the question with the html so you can see. If I change the width value from 100% to 20% for example, it doesn't change the size of the graph. You ckeck the here : boardlineapp.com/#faqPoriferous
I duplicated your chart (jsfiddle.net/asgallant/j3778edd) and don't have the same issues with dimensions. There is likely some CSS/javascript elsewhere on your site that is causing the problem.Plan
yes indeed it's weird ! Can you inspect the website boardlineapp.com/#faq and look if you find some interfering css ? Because I can't find anything...Thanks a lot for your helpPoriferous
I gave it a look over, but nothing popped out at me as immediately obvious. I suggest commenting out all of your code that is not directly related to the chart (all javascript and CSS) and re-enable it piece by piece until the chart breaks; then you've found the likely culprit behind your woes.Plan
I see that there is something weird: the div #chart_div actually takes the right size, but the chart inside stays at the same (too wide) size. Please look at the screen capture I've added in the question.Poriferous
N
6

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).

Navarrete answered 29/8, 2016 at 15:35 Comment(0)
C
4

put width 100% of the chart and call the resize function as below

$(window).resize(function(){
   yourCallingChartFunction();
});
Carcinomatosis answered 26/2, 2016 at 9:48 Comment(3)
Please give us some details on where width should be put (options, css, or anywhere else) and what getShotHistory meaning to us. That snippet only tell us to listen the resize event, no more.Doublebank
you must put your own function in place of getShotHistory();. I have created my own. You need to call the function where you have create chart functionality. $(window).resize(function(){ yourChartFunction(); }); You need provide the width 100% in your chartChartFunction();Carcinomatosis
I am assuming that you are using bootstrap for the responsive design. You need enclose the entire chart div inside the another div with some classes like col-sm-12 col-md-4, col-lg-4 or col-sm-12 col-md-6, col-lg-6 whatever you want as per the requirement.Carcinomatosis
C
2

For responsive on load works:

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

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

Camera answered 11/9, 2015 at 11:0 Comment(0)
M
2

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>
Mozzetta answered 16/2, 2017 at 22:30 Comment(3)
this seems to work, could you point me to some more tips tutorials I need to combine it with a responsive piehole overlay and center the legendMonetta
oh and should width be 100%??Monetta
@Monetta Where would you use 100%?Mozzetta
H
1

I've added a HostListener which listens if there's any change in the window size. And there I set the height and width of the Google Chart as follows-

@HostListener('window:resize', ['$event'])
onResize(event) {
this.width = $(window).width() * 0.35;
this.height = $(window).height() * 0.3;
}
Horologe answered 16/1, 2020 at 7:20 Comment(0)
H
0

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();
});
Heiner answered 14/4, 2016 at 8:54 Comment(0)
L
0

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);
})
}
Larkins answered 7/11, 2018 at 11:15 Comment(0)
G
0

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>
Gazelle answered 22/1, 2019 at 22:12 Comment(4)
This question is not really about "responsive charts", is about setting the width of the chart on load time.Sparrow
I guess you got downvoted because your solution do not workToscanini
You are right, the problem was on my side. I was drawing chart before DOM properly rendered so the chart rendered small. If you'll edit your question, I will revert my vote.Toscanini
Anything, SO doesn't allow to change rating after 15minutes(?) unless answer is edited. You can, for example, mention that you have to draw chart after DOM is rendered so person like me won't think your answer is incorrect.Toscanini
K
-1

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();
});
Kenti answered 11/6, 2015 at 10:14 Comment(1)
This can get very heavy very quickly as it will fire with every pixel that the window is resized. You are better off binding to the resize event and leaving a timeout to slow things down a bit.Heiner

© 2022 - 2024 — McMap. All rights reserved.