通过从下拉列表中进行多选来添加新堆栈,从而更新堆栈柱形图。我尝试做new Highcharts.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>
为什么不添加新堆栈?
答案 0 :(得分:1)
仅更改x
变量是不够的,您需要更改chartOptions.series
属性:
$(`#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);
});