【发布时间】:2021-05-11 23:08:21
【问题描述】:
我的输入数据具有不同数量的数据项和匹配数量的值项。我知道那里已经有图书馆,但我正在创建自己的图书馆;)
因此,如果有 3 列,则每列有 3 个值(就像 marimekko 图表一样):
我有以下数据虚拟输入,但它们的范围可以是任何正值:
const json = `{ "data": [
{ "value": [ 1, 2, 3, 4] },
{ "value": [ 5, 6, 7, 8] },
{ "value": [ 9, 10, 11, 12] },
{ "value": [13, 14, 15, 16] }
] }`
有了它,我得到了以下计算每列的总数(所以,[ 1, 5, 9, 13 ], [ 2, 6, 10, 14 ] ... etc:
const stackIndexTotal = (
dataJSON.slice(1).reduce( ( (sums, { value } ) =>
sums.map( ( sum, i ) => sum + value[ i ] )
), dataJSON[0].value )
);
目前我有这个代码和输出:
// dummy data
const json = `{ "data": [
{ "value": [ 1, 2, 3, 4] },
{ "value": [ 5, 6, 7, 8] },
{ "value": [ 9, 10, 11, 12] },
{ "value": [13, 14, 15, 16] }
] }`,
dataJSON = JSON.parse(json).data;
// find the sum of all the values at same index
const stackIndexTotal = (
dataJSON.slice(1).reduce(((sums, {
value
}) =>
sums.map((sum, i) => sum + value[i])
), dataJSON[0].value)
);
// loop the data
dataJSON.forEach((data, index) => {
// variables
const dataContainer = document.getElementById('data-container');
const dataItem = document.createElementNS('http://www.w3.org/2000/svg', 'g');
// inside the data:{}
const numberOfValues = dataJSON.length;
// loop the value array
data.value.forEach((item, i) => {
// inside the value:[]
const numberOfValueInArray = data.value.length;
const rectHeight = (item / stackIndexTotal[index]) * 100;
// 100 width view, divided by number of groups
const widthOfSections = (100 / numberOfValues);
// add in text items
dataItem.innerHTML += (
// the rectangle svg
// -- fill: dummy colours - each index, or same column has same colour
// -- x: offset of the xPosition
// -- width: fixed width for demo
// -- height: height of rect is percentage of arrays column total
// -- y: need to calculate offset
`<rect
fill="hsl(20, 30%, ${ ((100 / numberOfValues) * index) }%)"
x="${ (widthOfSections * i ) }"
width="${ widthOfSections }"
height="${ rectHeight }"
y="0"
></rect>`
);
});
// add into the DOM
dataContainer.appendChild(dataItem);
});
svg {
max-width: 25em;
max-height: 25em;
border: 2px solid;
margin: 2em 5em;
overflow: visible !important;
}
<svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet"><g id="data-container"></g></svg>
但希望得到以下输出。
这样,一旦我可以得到正确的偏移量,我就可以将所有值设为Math.max(...stackIndexTotal) 的百分比。
目前,我在两个循环中尝试的任何事情似乎都没有正确偏移块。我尝试获取以前的值:data.value[ i - 1 ],然后使用该百分比作为起点,但这似乎行不通。我尝试使用第一个循环index 来制作所有index === 0 ? 0,因此它们都从顶部开始,但是之后每个项目的偏移量似乎都关闭了。
【问题讨论】:
标签: javascript html css math svg