本文介绍了仅显示天数时间刻度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从scaleTime的x轴上删除月份和年份的刻度,但是不知道是否可能:
I'm trying to remove the month and year ticks from the x axis of a scaleTime, but don't know if it's possible:
我尝试使用tickFormat方法,但无法访问月份和年份的值.我只能通过将比例尺更改为linearScale并手动设置值的格式来获得预期的结果.
I've tried to use the tickFormat method but I cannot access the month and year values. I only get the expected results by changing the scale to a linearScale and formatting manually the values.
是否有可能按时标获得预期结果?
It is possible to get the expected result with a time scale?
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>
推荐答案
由于很难知道如何,轴生成器将显示时间刻度的刻度,因此建议您过滤创建后滴答作响:
Since it's hard to know how the axis generator is going to display the ticks for a time scale, I suggest that you filter the ticks after they were created:
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>
这篇关于仅显示天数时间刻度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!