使用Chartist我知道有一个选项可以在两个不同的数据集中“填补漏洞”,例如以下示例:
var chart = new Chartist.Line('.ct-chart', {
labels: [1, 2, 3, 4, 5, 6, 7],
series: [
[5, 5, 10, 8, 7, 5, 4],
[10, 15, null, 12, null, null, null]
]
}, {
lineSmooth: Chartist.Interpolation.cardinal({
fillHoles: true,
})
});
<script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<link href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css" rel="stylesheet"/>
<div class="ct-chart"></div>
在示例中,第二个系列将仅显示一个行,直到最后一个不是null
的值(在索引4处)。
有没有办法让宪章制作相对于第一个序列的第二个序列,扩展第二个序列线以匹配第一个序列,直到最长序列的最后一个值?
答案 0 :(得分:1)
您可以编写一些用于修改数据数组的助手:
trimNulls
从数组的开头和结尾删除任何null
值:
[10, 15, null, 12, null, null, null] -> [10, 15, null, 12]
stretch
接受一个数组和所需的长度,并将原始值分配给新索引:
[10, 15, null, 12] -> 7 -> [10, null, 15, null, null, null, 12]
alignSeries
列出一系列数据,并将每个数据系列与最宽的数据系列对齐。
[ [ 1, 2, 3, 4], [1, 4], [null, 1, 4] ] ->
[ [ 1, 2, 3, 4], [1, null, null, 4], [1, null, null, 4] ]
在一个正在运行的示例中,包括旧行以供参考:
const trimNulls = (data) => {
// Find the first non-null value
const start = data.findIndex(y => y !== null);
// Find the last non-null value
const end = data.length - Array.from(data).reverse()
.findIndex(y => y !== null);
// Return the elements between those boundaries
return data.slice(start, end);
}
const stretch = (data, newLength) => {
// Create array of required number of nulls
const stretched = Array(newLength).fill(null);
// Determine the stretch factor
const s = newLength / data.length;
// For every value we want to keep, place it
// at its new, stretched index
data.forEach((y, x) => {
stretched[Math.ceil(x * s)] = y;
});
// Return the newly created array
return stretched;
}
// Takes a list of series and aligns their starts and ends, stretching
// in between
const alignSeries = series => {
// Trim each series
const trimmed = series.map(trimNulls);
// Find the longest one
const maxLength = Math.max(...trimmed.map(t => t.length));
// Stretch all series to the longest length and return
return trimmed.map(t => stretch(t, maxLength));
};
var chart = new Chartist.Line('.ct-chart', {
labels: [1, 2, 3, 4, 5, 6, 7],
series: [
...alignSeries([
[5, 5, 10, 8, 7, 5, 4],
[10, 15, null, 12, null, null, null]
]),
// For reference
[10, 15, null, 12, null, null, null]
]
}, {
lineSmooth: Chartist.Interpolation.cardinal({
fillHoles: true,
})
});
<script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<link href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css" rel="stylesheet"/>
<div class="ct-chart"></div>