2012-11-15 59 views
1

我的數據是d的格式[對象,對象,....]其中每個對象的形式是{計數:5時間:1352961975},其中時間是Unix時間戳。我想根據時間和計數值來繪製這個圖。計數值被繪製在y軸和與時間將x軸繪製爲上午12點30,上午01時,上午01時半...。到當前時間。
這樣d3.js繪製時間序列分的曲線圖

var midnight_time = new Date(); 
    midnight_time.setHours(0,0,0,0); 


    x = d3.time.scale() 
    .range([0,width]) 
    .domain([ new Date(midnight_time),new Date()]); 

    y = d3.scale.linear() 
    .domain([0,ymax]) //by using ajax not shown here getting the value of ymax      
    .range([height, 0]); 

line = d3.svg.line() 
.x(function(d) { return x(d.count); }) 
.y(function(d) { return y(d.time); }); 

svg = d3.select("#viz").append("svg") 
.attr("width", width + margin.left + margin.right) 
.attr("height", height + margin.top + margin.bottom) 
.append("g") 
.attr("transform", "translate(" + margin.left + "," + margin.top + ")"); 


    svg.append("defs").append("clipPath") 
    .attr("id", "clip") 
    .append("rect") 
    .attr("width", width) 
    .attr("height", height); 

svg.append("g") 
    .attr("class", "x axis") 
    .attr("transform", "translate(0," + height + ")") 
    .call(d3.svg.axis().scale(x).orient("bottom") 
    .ticks(d3.time.minutes,tick_count)); 

svg.append("g") 
    .attr("class", "y axis") 
    .call(d3.svg.axis().scale(y).orient("left")); 

    d3.select(".x.axis") 
    .append("text") 
     .text("the time span") 
    .attr("transform", "translate(360,30)"); 


    d3.select(".y.axis") 
    .append("text") 
    .text("Maximum number of active users") 
    .attr("transform", "rotate (-90, -35, 0) translate(-210)"); 

path = svg.append("g") 
    .attr("clip-path", "url(#clip)") 
    .append("path") 
    .data([data]) 
    .attr("class", "line") 
    .attr("d", line); 

我想我不應用正確格式化時間。我需要Unix的時間戳正確的時間在上午或下午的格式,然後調用相應圖形繪製轉換。

回答

2

Unix時間戳沒有上午或下午的概念,要處理,採用格式化。 D3用於創建時間格式可以讓你指定它出現正是你想要的(見this documentation)提供的功能。然後,您可以在格式傳遞給軸與tickFormat方法。

我認爲格式化字符串%I:%M %p會給你你想要的格式。你會用類似這樣的東西:

d3.svg.axis().scale(y).orient("left").tickFormat(d3.time.format("%I:%M %p"))