我正在嘗試使用 svg 和 html 創建堆疊條形圖,而不使用任何 3rd 方庫。不幸的是,沒有在線檔案顯示如何使用普通 svg 創建堆疊條形圖。
我已經創建了一個代碼筆,我正在實作該堆疊條形圖。任何人都可以讓我知道還需要什么才能使它成為堆疊條形圖。

uj5u.com熱心網友回復:
要堆疊條形圖,您需要計算當前列和空間寬度。將svg包裝到div,還將文本偏移到div并以display:flex.
將y鍵添加到bar,其中:
- 起點 =通過= 0
- 中間點 =跳過=傳遞值
- 終點 =失敗=傳遞值 跳過值
y: key === 'passed' ? 0 : key === 'skipped' ? d['passed'] : d['skipped'] d['passed'],
// Basic style
const newCardStyle = {
display: 'flex',
};
const contentStyle = {
display: 'flex',
flexFlow: 'column',
alignItems: 'center',
};
// multiply 50 (width) * 3 (columns) 10 (space width) * 2 ( space between columns)
const width = 50 * 3 10 * 3;
function App() {
const data = [
{
name: 'Transit',
passed: 2,
skipped: 5,
failed: 22,
},
{
name: 'Access',
passed: 7,
skipped: 2,
failed: 11,
},
];
// Basic style
const newCardStyle = {
display: 'flex',
};
const contentStyle = {
display: 'flex',
flexFlow: 'column',
alignItems: 'center',
};
// multiply 50 (width) * 3 (columns) 10 (space width) * 2 ( space between columns)
const width = 50 * 3 10 * 3;
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],
y:
key === 'passed'
? 0
: key === 'skipped'
? d['passed']
: d['skipped'] d['passed'],
}))
.filter(bar => bar.value),
}));
const rows = entry => {
return entry.bars.map((bar, index) => {
const height = (bar.value / entry.total) * 100;
const y = (bar.y / entry.total) * 100;
return (
<g key={Math.random()}>
<rect
width={50}
height={`${height}%`}
fill={bar.color}
x={60} // multiply with the width (50) 10 for space
y={`${y}%`}
/>
</g>
);
});
};
return (
<div className="new-card" style={newCardStyle}>
{entries.map(entry => (
<div style={contentStyle} key={Math.random()}>
<svg
viewBox={`0, 0, ${width}, ${500}`}
height={500}
width={width}
style={{ transform: `rotateX(180deg)` }}
>
{rows(entry)}
</svg>
{entry.name}
</div>
))}
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
<script src="https://unpkg.com/react@17/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" crossorigin></script>
<div id="root"></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/361879.html
標籤:javascript html css 反应 svg
