How to use sparse arrays with C3 charts?

你说的曾经没有我的故事 提交于 2019-12-13 03:37:17

问题


For graphing in C3, we can give it column data, which is an array of arrays with each array being a different line on the chart like in this C3 docs example. But is there a way to have that column data sparse? I'm getting an error when I try that, although I'm not sure if there's a workaround I don't know about.

If not, is there a better way to convert between sparse and dense arrays than a filter function like what I have?

https://jsfiddle.net/dbkidd/majx8byn/

var columnData = []

var entry1 = ['data1', 30, 200, 100, 400, 150, 250];
var entry2 = ['data2', 50, 20, 10, 40, 15, 25];

columnData[0] = entry1;
columnData[3] = entry2;
console.log('columnData - sparse format', JSON.stringify(columnData));

function checkIfUndefined(x) {
    return (x !== undefined);
}

function sparseToDense(data) {
  return data.filter(checkIfUndefined);
}

/* If you comment out this sparseToDense conversion, it breaks
 * with the following error:
 * c3.js:5403 Uncaught TypeError: Cannot read property '0' of undefined
*/
columnData = sparseToDense(columnData);
console.log('columnData - dense format', JSON.stringify(columnData));

var chart = c3.generate({
    data: {
        columns: columnData,
        axes: {
            data1: 'y',
            data2: 'y2'
        }
    },
    axis: {
        y2: {
            show: true
        }
    }
});

回答1:


You can use empty array as entry value. This works ok:

[["data1",30,200,100,400,150,250],[],[],["data2",50,20,10,40,15,25]]

And modify your filtering function to skip arrays without length:

function checkIfNull(x) {
    return (x.length);
}

See updated fiddle



来源:https://stackoverflow.com/questions/47295727/how-to-use-sparse-arrays-with-c3-charts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!