2017-03-02 32 views
0

我試圖刪除月份和年份從scaleTime的x軸蜱,但不知道這是否是可能的:只顯示scaleTime天蜱

xAxis of scaleTime

我試着要使用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>

回答

1

因爲很難知道如何軸發電機將要顯示的刻度的時間尺度,我建議您篩選蜱他們被創建後:

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>