我正在尝试从scaleTime的x轴上删除月份和年份刻度,但不知道是否可能:
我尝试使用tickFormat 方法,但无法访问月份和年份值。我只能通过将比例更改为 LinearScale 并手动格式化值来获得预期结果。
有可能在时间尺度上得到预期的结果吗?
const margin = { top: 20, right: 20, bottom: 20, left: 20 };
const width = 1000 - margin.top - margin.bottom;
const height = 100 - margin.left - margin.right;
const totalWidth = width + margin.top + margin.bottom;
const totalHeight = height + margin.left + margin.right;
let svg = d3.select('.chart')
.append('svg')
.attr('width', totalWidth)
.attr('height', totalHeight)
.append('g')
.attr('transform', `translate(${margin.left},${margin.top})`);
let xScale = d3.scaleTime()
.rangeRound([0, width])
.domain([
new Date(1482883200000), // 2016-12-28
new Date(1485993600000) // 2017-02-02
]);
let xAxis = d3
.axisBottom(xScale);
svg.call(xAxis);
<script src="https://d3js.org/d3.v4.min.js"></script>
<div class="chart"></div>
最佳答案
由于很难知道轴生成器将如何显示时间刻度的刻度,因此我建议您在创建刻度后对其进行过滤:
d3.selectAll(".tick").each(function(d) {
if (d3.timeFormat("%Y")(d) == d3.select(this).text() ||
d3.timeFormat("%B")(d) == d3.select(this).text()) {
d3.select(this).remove();
}
})
这是演示:
const totalWidth = 800;
const totalHeight = 100;
let svg = d3.select('body')
.append('svg')
.attr('width', totalWidth)
.attr('height', totalHeight);
let xScale = d3.scaleTime()
.rangeRound([20, totalWidth - 20])
.domain([
new Date(1482883200000), // 2016-12-28
new Date(1485993600000) // 2017-02-02
]);
let xAxis = d3.axisBottom(xScale);
svg.append("g").attr("transform", "translate(0,40)").call(xAxis);
var format = d3.timeFormat("%a %d");
d3.selectAll(".tick").each(function(d) {
if (d3.timeFormat("%Y")(d) == d3.select(this).text() || d3.timeFormat("%B")(d) == d3.select(this).text()) {
d3.select(this).remove();
}
})
<script src="https://d3js.org/d3.v4.min.js"></script>
关于javascript - 仅显示天数时间刻度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42554514/