2012-11-15 60 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"))