【发布时间】:2021-12-30 23:55:24
【问题描述】:
我正在尝试使用 svg 和 html 创建一个堆叠的条形图,而不是使用任何 3rd 方库。不幸的是,没有一个在线文档显示如何使用纯 svg 创建堆叠条形图。
我已经创建了一个 codepen,并且我正在实现那个堆叠的条形图。任何人都可以让我知道还需要什么来制作这个堆叠的条形图。
https://codepen.io/a166617/pen/qBXvzQd
这是我目前拥有的代码
const ReleaseScopeCharts = () => {
const data = [
{
name: 'Transit',
passed: 2,
skipped: 5,
failed: 22,
},
{
name: 'Access',
passed: 7,
skipped: 2,
failed: 11,
},
];
const width = 500;
const colors = ['#30D158', '#005EA7', '#FF453A'];
const entries = data.map((d) => ({
name: d.name,
total: ['passed', 'skipped', 'failed'].reduce((acc, key) => acc + d[key], 0),
bars: ['passed', 'skipped', 'failed'].map((key, i) => ({
value: d[key],
color: colors[i],
}))
.filter((bar) => bar.value),
}));
const rows = (entry) => entry.bars.map((bar, index) => {
const height = (bar.value / entry.total) * 100;
return (
<g key={index}>
<rect
width={50}
height={`${height}%`}
fill={bar.color}
x={index * 60} // multiply with the width (50) + 10 for space
/>
</g>
);
});
return (
<div className="new-card">
<div />
{entries.map((entry) => (
<>
{entry.name}
<svg viewBox={`0, 0, ${width}, ${500}`}
height={500}
width={width}
style={{ transform: `rotateX(180deg)` }}
>
{rows(entry)}
</svg>
</>
))}
</div>
);
};
对于堆积条形图,我的意思是显示一个在另一个之上。
【问题讨论】:
标签: javascript html css reactjs svg