nb_nb_nb
nb_nb_nb

Reputation: 1381

Update highcharts with new set of data

Update stacked column charts by adding new stacks by multi-select from dropdown. I try to do new Highcharts.chart(...) I am not getting new stacks drawn. When I recreate it, I am at least still getting the previous chart to remain. No another recreation, on-select I cam just getting a blank chart.

const obj = {
'10-10-2020': [
  {cat: 'cat', abc: 1, xyz: 5, pqr: 6, jkl: 1, mno: 9},
  {cat: 'dog', abc: 3, xyz: 4, pqr: 1, jkl: 6, mno: 1},
  {cat: 'rat', abc: 7, xyz: 2, pqr: 9, jkl: 3, mno: 0},
  ],
'10-07-2020':[
  {cat: 'cat', abc: 1, xyz: 5, pqr: 6, jkl: 1, mno: 9},
  {cat: 'dog', abc: 3, xyz: 4, pqr: 1, jkl: 6, mno: 1},
  {cat: 'rat', abc: 7, xyz: 2, pqr: 9, jkl: 3, mno: 0},
  ],
'10-09-2020':[
  {cat: 'cat', abc: 1, xyz: 5, pqr: 6, jkl: 1, mno: 9},
  {cat: 'dog', abc: 3, xyz: 4, pqr: 1, jkl: 6, mno: 1},
  {cat: 'rat', abc: 7, xyz: 2, pqr: 9, jkl: 3, mno: 0},
  ],
};

const colors=['#000', 'red', 'blue'];
let arr = ['abc', 'xyz', 'pqr', 'jkl', 'mno'];

const data = (sd) => Object.entries(obj).map(([k, g]) => ({
  ['name']: k,
  ['data']: g.map(entry => entry[sd]),
  ['stack']: sd,
  ['color']: colors[i++ % colors.length],
}));


let i = 0;
let x = data('abc');


 let chartOptions={   chart: {
        type: 'column'
    },

    xAxis: {
        categories: ['One', 'Two', 'Three', 'Four', 'Five']
    },

    plotOptions: {
        column: {
            stacking: 'normal'
        }
    },

    series: x 
    }

arr.forEach(c => {$(`#mydropdown`).append(`<option value='${c}'>${c}</option>`);});
$(`select#mydropdown option[value='abc']`).prop('selected', 'selected');

$(`#mydropdown`).on('change', function() {
   x = [];
   $('option:selected', this).each(function() {
      i = 0;
			x = [...x, ...data($(this).val())];
   });
   console.log(x);
   new Highcharts.chart('container', chartOptions);
});

let mychart = new Highcharts.chart('container', chartOptions);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>

<select multiple id="mydropdown"></select>
<div id="container" style="height: 400px"></div>

Why aren't the new stacks getting added?

Upvotes: 1

Views: 50

Answers (1)

ppotaczek
ppotaczek

Reputation: 39149

Changing x variable is not enough, you need to change chartOptions.series property:

$(`#mydropdown`).on('change', function() {
    x = [];
    $('option:selected', this).each(function() {
        i = 0;
        x = [...x, ...data($(this).val())];
    });
    chartOptions.series = x;
    new Highcharts.chart('container', chartOptions);
});

Live demo: http://jsfiddle.net/BlackLabel/0hq2c1r4/

Upvotes: 1

Related Questions