我只是想創建一個標記為 1 月到 12 月的 y 軸,但我不明白為什么我的代碼會創建:January, March , March , April .... December。有人可以向我解釋一下嗎?謝謝!
const w = 1078;
const h = 666;
const padding = 70;
const svg = d3
.select("#svg-container")
.append("svg")
.attr("width", w)
.attr("height", h);
const months = Array(12)
.fill(0)
.map((v, i) => new Date().setMonth(i));
const yScale = d3
.scaleTime()
.domain([months[11], months[0]])
.range([h - padding, padding]);
const yAxis = d3
.axisLeft(yScale)
.tickValues(months)
.tickFormat(d3.timeFormat("%B"));
svg
.append("g")
.attr("transform", "translate(" padding ", -20)")
.attr("id", "y-axis")
.call(yAxis);
body {
background: gray;
}
svg {
background: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="svg-container"></div>
uj5u.com熱心網友回復:
發生這種情況是因為setMonth()還設定了您當前所在的日期。今天是第 30 天,而 2021 年 2 月只有 28 天,因此不存在的 2021 年 2 月 30 日實際上是 2021 年 3 月 2 日。如果您將日期列印在不同的格式:

要解決此問題,您可以使用完整的日期功能 new Date(2021, i, 1)
const w = 1078;
const h = 666;
const padding = 70;
const svg = d3
.select("#svg-container")
.append("svg")
.attr("width", w)
.attr("height", h);
const months = Array(12)
.fill(0)
.map((v, i) => new Date(2021, i, 1));
const yScale = d3
.scaleTime()
.domain([months[11], months[0]])
.range([h - padding, padding]);
const yAxis = d3
.axisLeft(yScale)
.tickValues(months)
.tickFormat(d3.timeFormat("%B %d"));
svg
.append("g")
.attr("transform", "translate(" padding ", -20)")
.attr("id", "y-axis")
.call(yAxis);
body {
background: gray;
}
svg {
background: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="svg-container"></div>
30號發這個對你有好處,否則會有隱藏的bug等著出現!
其他資源
MBostock 的月軸示例:https ://bl.ocks.org/mbostock/1849162
D3 Scaletime 檔案:https ://observablehq.com/@d3/d3-scaletime
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/401968.html
標籤:d3.js
