55

I'm using Highcharts within Zurb's Foundation framework for a class project. I have three charts within a section tab. One is within a 12-column div, the other two are on the same row within 6-column divs.

When the page loads, the featured chart does not take up the available width of the 12 columns, and the two smaller charts overflow their 6 columns. However, when the window is resized or I try to investigate using Inspect element, the charts immediately snap into the correct dimensions. This behavior occurs in Chrome, FF, and IE.

I realize I could set a specific width, but I'd really like to take advantage of Foundation and keep them responsive.

I've tweaked the CSS and Highcharts initializations, but I'm stumped. Has anyone else experienced this issue? Can anyone see what I'm missing?

Here's an excerpt from my HTML:

<div class="row">
<div class="twelve columns">
    <!--begin tabs below--> 
    <div class="section-container tabs" data-section="tabs">
      <section>
        <p class="title" data-section-title><a href="#">Heart Disease</a></p>
        <div class="content" data-section-content id="heart">

            <div class="row feature-chart">
                <div class="large-12 columns">
                    <div id="heartTimeline-container">
                    <div id="heartTimeline"></div>
                    </div>
                </div> <!--close 12 columns-->
            </div> <!--close row-->
            <div class="row small-charts">
                <div class="large-6 columns">
                    <div id="heartDemo"></div>
                </div>
                <!--close 6-->
                <div class="large-6 columns">
                    <div id="heartStages"></div>
                </div>
                <!--close 6-->
            </div>
            <!--end row-->
        </div>
      </section>
   </div>
   </div>
   <!--end twelve columns-->

Here's the Highcharts js:

$(function () {
    Highcharts.setOptions({
        colors: ['#1A1A1A', '#455D78', '#BDCCD4', '#999999', '#B3B3B3', '#F2F2F2']
    });
    $('#heartTimeline').highcharts({
        chart: {
            type: 'area'
        },
        title: {
            text: 'Heart Disease Death Rates in the U.S.from 1980-2010'
        },
        subtitle: {
            text: 'Source: <a href="http://www.mdch.state.mi.us/pha/osr/deaths/Heartdx.asp">'+ 
                        'Michigan Department of Community Health</a>'
        },
        xAxis: {
            labels: {
                formatter: function() {
                    return this.value; // clean, unformatted number for year
                }
            }
        },
        yAxis: {
            title: {
                text: 'Heart Disease Death Rate Per 100,000 People'
            },
            labels: {
                formatter: function() {
                    return this.value / 1 +'k';
                }
            }
        },
        tooltip: {
            pointFormat: '{series.name} produced <b>{point.y:,.0f}</b><br/>deaths per hundred thousand people in {point.x}'
        },
        plotOptions: {
            area: {
                pointStart: 1980,
                marker: {
                    enabled: false,
                    symbol: 'circle',
                    radius: 2,
                    states: {
                        hover: {
                            enabled: true
                        }
                    }
                }
            }
        },
        series: [{
            name: 'Heart Disease',
            data: [412.1, 397, 389, 388, 378, 375, 365.1, 355.9, 352.5, 332, 321.8, 313.8, 306.1, 309.9, 299.7, 296.3, 288.3, 280.4, 272.4, 267.8, 257.9, 247.8, 240.8, 232.3, 217, 211.1, 200.2, 190.9, 186.5, 180.1, 178.5]
        }, ]
    });
});
$(function () {
    $('#heartDemo').highcharts({
        chart: {
            zoomType: 'xy'
        },
        title: {
            text: 'Most Prevelant Causes and Effects of Heart Disease 2013'
        },
        subtitle: {
            text: 'Source: http://circ.ahajournals.org (The American Heart Association)'
        },
        xAxis: [{
            categories: ['Smoking', 'Obesity (BMI > 25 kg) ', 'Total cholesterol > 200 mg)', 'High Blood Pressure', 'Diabetes Mellitus', 'Prediabetes', 'Total Cardiovascular Disease', 'Stroke', 'Coronary Heart Disease', 'Heart Failure'],
            labels: {
                rotation: -90,
                align:'right'
            }
        }],
        yAxis: [{ // Primary yAxis
            labels: {
                formatter: function() {
                    return this.value +'%';
                },
                style: {
                    color: '#000000'
                }
            },
            title: {
                text: 'Men',
                style: {
                    color: '#BDCCD4'
                }
            },
            opposite: true

        }, { // Secondary yAxis
            gridLineWidth: 0,
            title: {
                text: 'Both Sexes',
                style: {
                    color: '#455D78'
                }
            },
            labels: {
                formatter: function() {
                    return this.value +' %';
                },
                style: {
                    color: '#4572A7'
                }
            }

        }, { // Tertiary yAxis
            gridLineWidth: 0,
            title: {
                text: 'Women',
                style: {
                    color: '#AA4643'
                }
            },
            labels: {
                formatter: function() {
                    return this.value +' %';
                },
                style: {
                    color: '#AA4643'
                }
            },
            opposite: true
        }],
        tooltip: {
            shared: true
        },
        legend: {
            layout: 'vertical',
            align: 'left',
            x: 120,
            verticalAlign: 'top',
            y: 80,
            floating: true,
            backgroundColor: '#FFFFFF'
        },
        series: [{
            name: 'Both Sexes',
            color: '#455D78',
            type: 'column',
            yAxis: 1,
            data: [19, 68.2, 43.4, 33, 8.3, 38.2, 35.3, 2.8, 6.4, 2.1],
            tooltip: {
                valueSuffix: ' %'
            }
        }, {
            name: 'Women',
            type: 'spline',
            color: '#AA4643',
            yAxis: 2,
            data: [16.7, 63.7, 44.9, 32.2, 7.9, 30.5, 34, 3, 5.1, 1.8],
            marker: {
                enabled: false
            },
            dashStyle: 'shortdot',
            tooltip: {
                valueSuffix: ' %'
            }
        }, {
            name: 'Men',
            color: '#BDCCD4',
            type: 'spline',
            data: [21.3, 72.9, 41.3, 33.6, 8.7, 46, 36.7, 2.6, 7.9, 2.5],
            tooltip: {
                valueSuffix: ' %'
            }
        }]
    });
});

$(function () {
    $('#heartStages').highcharts({
        chart: {
            type: 'column'
        },
        title: {
            text: 'Number of Deaths for Different Types of Heart Diseases in the U.S. for 2008'
        },
        subtitle: {
            text: 'Source: <a href="http://www.nhlbi.nih.gov/resources/docs/2012_ChartBook_508.pdf">'+ 
                'Morbitity & Mortality: 2012 Chart Book on Cardiovascular, Lung and Blood Disease</a>'
        },
        xAxis: {
            categories: [
                'Coronary Heart Disease',
                'Heart Attack',
                'Cardiomyopathy',
                'Stroke',
                'Atrial Fibrillation and Flutter',
                'Heart Failure',
                'Diseases of Pulmonary Circulation',
                'Pulmonary Embolism',
            ],
            labels: {
                rotation: -90,
                align:'right'
            }
        },
        yAxis: {
            min: 0,
            title: {
                text: 'Heart Disease Diagnostic Category (thousands)'
            }
        },
        tooltip: {
            headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
            pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                '<td style="padding:0"><b>{point.y:.1f} </b></td></tr>',
            footerFormat: '</table>',
            shared: true,
            useHTML: true
        },
        plotOptions: {
            column: {
                pointPadding: 0.2,
                borderWidth: 0
            }
        },
        series: [{
            name: 'Heart Disease Related Deaths for 2008',
            data: [405.309, 133.958, 23.932, 134.148, 15.383, 56.830, 12.927, 7.158]

        }]
    });
});
Mick
  • 6,527
  • 4
  • 52
  • 67
user2313761
  • 551
  • 1
  • 4
  • 3
  • Old question but was this error ever resolved? I am encountering the same error and have tried the solutions listed below including calling `highcharts.reflow()` but nothing is seeming to work – wmash Nov 27 '15 at 07:23

12 Answers12

38

I got this from another answer, so give thegreyspot some credit in this question.

solution: call $(window).resize(); after the graph is loaded (or when you fill it with data)

Community
  • 1
  • 1
Bob Vork
  • 2,927
  • 28
  • 32
  • 1
    Tried this, it actually collapses the graph to minimum width for available elements. – Eric Hodonsky Jul 10 '14 at 20:33
  • 4
    For me it doesn't work. And it would not be the right solution: you could have different actions / behaviours defined in the resize event handler, sometimes they could be heavy to execute or they could make ajax call for data reload.. don't know.. It doesn't settle me down. – andrea.rinaldi Oct 02 '14 at 08:56
  • 1
    Changed nothing for me – Jerome Jan 25 '17 at 15:09
21

Just use the chart.reflow() function

Kromster
  • 7,181
  • 7
  • 63
  • 111
Adelos
  • 418
  • 3
  • 5
19

Please take a look at these examples with responsive highcharts:

http://jsbin.com/anuqav/1/edit

http://jsfiddle.net/2gtpA/show/

<div id="container" style="width:100%;margin: 0 auto"></div>
ry8806
  • 2,258
  • 1
  • 23
  • 32
Sebastian Bochan
  • 37,348
  • 3
  • 49
  • 75
9

This might help:

$(Highcharts.charts).each(function(i,chart){
    var height = chart.renderTo.clientHeight; 
    var width = chart.renderTo.clientWidth; 
    chart.setSize(width, height); 
  });
Tejpal Sharma
  • 432
  • 6
  • 14
  • where would this code go? i added under the 'load' event, no dice. please advise. – Jess Jacobs Nov 19 '15 at 01:20
  • @JessicaJacobs In the load callback function events: { load: function(event) { redrawCharts(); } } function redrawCharts() { $(Highcharts.charts).each(function(i,chart){ var height = chart.renderTo.clientHeight; var width = chart.renderTo.clientWidth; chart.setSize(width, height); }); } – Tejpal Sharma Jan 24 '16 at 11:33
  • Please note that explicitly setting fixed width values using `chart.setSize()` will "freeze" the dimensions of the chart until you force a resize event. You can use percentage values for width and height here to avoid that. – Mike Zavarello Jun 03 '16 at 02:03
  • To only trigger a resize you can now (since Highcharts v.2.4.6) invoke the setSize function with 2 null parameters to resize to the containing element. When execution asynchronously it works like a charm: setTimeout(function () { $(Highcharts.charts).each(function (i, chart) { chart.setSize(); }); }, 1); – Vapour in the Alley Sep 22 '16 at 12:16
  • changed nothing for me – Jerome Jan 25 '17 at 15:16
  • This was the **only** solution I've found that fixes the chart widths without causing any visible glitches on load. When called simply as `chart.setSite();` as @VapourintheAlley's suggests, it adds hardly any processing overhead at all. :D –  Sep 01 '17 at 16:54
4

for me, it needed to take some delay and trigger the window resize.

window.setTimeout(function(){ $(window).trigger('resize'); }, 500);
aungye
  • 2,219
  • 1
  • 15
  • 6
  • For me, the only thing that worked was putting this after my chart initialisation code `window.setTimeout(function(){ myChart.reflow(); });`, I didn't have any luck with triggering a resize. – NibblyPig Jun 14 '19 at 08:57
3

You can add an event listener so your chart resizes every time it redraws:

mychart = new Highcharts.stockChart('div',   {
    chart: {
        events: {
            redraw: function(e) {
                mychart.reflow();
            }
        }
    },
2

In pure javascript multiple charts in single page resize issue on window resize

 window.onresize = function() {
    //- Remove empty charts if you are using multiple charts in single page 
    //- there may be empty charts
    Highcharts.charts = Highcharts.charts.filter(function(chart){
        return chart !== undefined;
    });

    Highcharts.charts.forEach(function(chart) {
        var height = chart.renderTo.chartHeight;
        //- If you want to preserve the actual height and only want to update 
        //- the width comment the above line.
        //- var height = chart.chartHeight; 
        var width = chart.renderTo.clientWidth;
        //- The third args is an animation set to true. 
        chart.setSize(width, height, true);
    });
};

We need this css code as well

.highcharts-container {
    width: 100%;
}
.highcharts-container svg {
    width: 100%;
    display: flex;
}
1

Sort of an old topic now, but I had this issue with IE8. The current version of IE at the time of writing this is IE10, but I needed to make my site compatible with earlier versions. The solution that worked for me was a combination of above and other sites where people spoke about the solution they implemented. I went for a settimeout plus a resize and just executed for IE8, I hope this helps someone else like myself who tried to find a solution for a few hours.

You may find just the script section is the only section you require.

<!--[if IE 8]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  <script>
    function timeout() {
        $(window).resize();
    }
    window.setTimeout(function() {
        timeout();
    },2000);
  </script>
  <style>
    .highcharts-container{width:100% !important; height:100% !important;}
  </style>
<![endif]-->
1

You can use this code for the example

var chart;
$(function() {
  var newh = $("#container").height();
    $( window ).resize(function() {
    newh = $("#container").height();
    chart.redraw();
    chart.reflow();
  });
  chart = new Highcharts.Chart();
})

http://jsfiddle.net/Behseini/qheh4w0n/

km4Guarana
  • 13
  • 4
0

only this worked for me

$(window).resize(function(){ 
    $scope.chartConfig.getChartObj().reflow() 
});
Michal Orlík
  • 501
  • 4
  • 3
0

Just want to add another solution:

$('.chart').highcharts(options, function(chart) {
  setTimeout(function() {
    chart.reflow();
  });
});

What it does is reflowing the chart the next frame after it has been rendered.

Sơn Trần-Nguyễn
  • 2,188
  • 1
  • 26
  • 30
-3
$(Highcharts.charts).each(function(i,chart){
    var height = chart.renderTo.clientHeight; 
    var width = chart.renderTo.clientWidth; 
    chart.setSize(width, height);
    });

it works for me

Palani
  • 7