2016-01-06 27 views
1

我試圖創建一個包含星期編號的軸。然而,由於軸遵循一個特殊的規則,我不能用正常的時間尺度:在一週的第一天1點開始創建具有不規則刻度的軸

每一年,周

這意味着,在結束每年,有可能會形成一個完整的星期天,在新的一年後開始再次第1周:

enter image description here

可以這樣使用D3時間軸上進行,從而受益於所有善良的善良?

回答

1

您可以使用tickFormat函數執行此操作。下面是比較默認與去年格式的周格式化的例子:

<!DOCTYPE html> 
<meta charset="utf-8"> 
<style> 

body { 
    font-family: sans-serif; 
    color: #444; 
} 


.axis path, 
.axis line { 
    fill: none; 
    stroke: #000; 
    shape-rendering: crispEdges; 
} 
.axis text { 
    font-size: 10px; 
} 

</style> 
<body> 

<h4>Week of Year Example</h4> 

<div id="svg"></div> 

<script src="https://d3js.org/d3.v3.min.js"></script> 
<script> 

var hEach = 40; // height for each axis 
var width = 960, 
    height = 2*hEach; 

var x = d3.time.scale() 
    // month starts from 0! 
    .domain([new Date(2015, 11, 1), new Date(2016, 0, 30)]) 
    .range([0, width]); 

var xAxis = d3.svg.axis() 
    .scale(x) 
    .orient("bottom"); 

// Week of year 
var xAxis_woy = d3.svg.axis() 
    .scale(x) 
    .tickFormat(d3.time.weekOfYear) 
    .orient("bottom"); 

var svg = d3.select("#svg").append("svg") 
    .attr("width", width) 
    .attr("height", height) 
    .append("g") 

var gx = svg.append("g") 
    .attr("class", "x axis") 
    .attr("transform", "translate(0," + (.5*hEach) + ")") 

    .call(xAxis); 

var gx_woy = svg.append("g") 
    .attr("class", "x axis") 
    .attr("transform", "translate(0," + (1.5*hEach) + ")") 
    .call(xAxis_woy); 


</script> 

Output

enter image description here

你可以閱讀更多關於d3.timehere,並.tickFormathere

+0

@adilapapaya嗨 - 感謝爲了這。但是你的1-tick是在1月3日以下;應該是1月1日。這不是關於如何格式化刻度標籤的問題。 –

+0

@RobertGrant您可以將任何函數傳遞給'.tickFormat' ...只需用您自己的自定義版本替換上面的'd3.time.weekOfYear',該版本接受'Date'對象並將標籤輸出到您的規範。我想你可以通過結合指定'.tickValues'來完成你想要的工作(所以你的滴答去1月1日,2008年1月,...) – adilapapaya

+0

嗯,我明白你的意思。對於之前的信息抱歉 - 你可能是對的。我會試一試! –