John Doe
John Doe

Reputation: 2924

d3.js plotting the graph on time series scale

My data is in the format of d [ Object, Object,.... ] where each object is of the form {count:5 time:1352961975 },where time is Unix Timestamp. I want to plot this on the basis of time as against the count value. The count value is being plotted on y-axis and and the time will be plotted on x-axis as 12:30 AM , 1 AM, 1:30 AM ... . to the current-time.
like this

  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);

I think I am not applying the time formatting correctly. I need to convert the Unix timestamp to correct Time in AM OR PM format and then call graph plotting accordingly.

Upvotes: 1

Views: 3045

Answers (1)

Freaky Dug
Freaky Dug

Reputation: 1035

The UNIX timestamp has no concept of AM or PM, you want to handle that using a formatter. d3 provides functions for creating a time formatter which will let you specify it to appear exactly as you want (see this documentation). You can then pass that formatter to the axis with the tickFormat method.

I think the formatting string %I:%M %p would give you the format you want. You would apply this with something like:

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

Upvotes: 2

Related Questions