這類的 API 是直接拿一整個完整的資料集去繪製完整的圖表
程式碼
// html
<svg class="stack"></svg>
//JS
const dataStack = [
{ month: new Date(2023, 0, 1), China: 132, America: 120, Taiwan: 30 },
{ month: new Date(2023, 1, 1), China: 70 , America: 127, Taiwan: 98 },
{ month: new Date(2023, 2, 1), China: 130, America: 33 , Taiwan: 118 },
{ month: new Date(2023, 3, 1), China: 60 , America: 90 , Taiwan: 60 },
];
// 設定資料的keys
const stackGenerator = d3.stack().keys(["China", "America", "Taiwan"]);
// 把資料帶入stack方法
const stackedSeries = stackGenerator(dataStack);
console.log("stack", stackedSeries);
// 設定顏色
const colorScale = d3
.scaleOrdinal()
.domain(["China", "America", "Taiwan"])
.range(["red", "blue", "orange"]);
// 建立集合元素g、設定顏色
const g = d3
.select(".stack")
.attr("width", 300)
.selectAll("g")
.data(stackedSeries)
.enter()
.append("g")
.attr("fill", (d) => colorScale(d.key));
// 繪製長條圖
g.selectAll("rect")
.data((d) => d)
.join("rect")
// 長度為終點值減起始值
.attr("width", (d) => d[1] - d[0])
// x 座標設定為起始值
.attr("x", (d) => d[0])
// y 座標用 index 來處理,乘上每條長條圖想拉開的距離
.attr("y", (d, i) => i * 35)
.attr("height", 20);