Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New to nvD3 - how can I make my unix timestamps appear as dates on the x-axis?

Tags:

d3.js

nvd3.js

Due disclosure - I am awful at javascript, but trying to learn!

I have an array with a few entries like these in it:

[1349013600] => 232

The key is a unix timestamp, the value is the $ in sales from that day. I am currently graphing these on a multibar chart, which is working great.

The problem is my x-axis, which is currently defined like this:

chart.xAxis
.tickFormat(d3.format(',f'));

It outputs the unix timestamp as a straight int against the x-axis labels and hover tooltip. I want to try and get it to output as D-M-Y or a similar human readable date indicator.

The closest I have found is this bit of code:

chart.xAxis.tickFormat(function(d) {
       var dx = testdata[0].values[d] && testdata[0].values[d].x || 0;
   return d3.time.format('%x')(new Date(dx))
 });

But I am struggling to understand what it's doing and can't implement on my particular chart. Current code looks like this:

nv.addGraph(function() {
var chart = nv.models.multiBarChart()
            .stacked(true)

chart.xAxis
    .tickFormat(d3.format(',f'));

chart.yAxis
    .tickFormat(function(d) { return '$' + d3.format(',f')(d) });

d3.select('#chart1 svg')
    .datum(test_data2)
  .transition().duration(500).call(chart);

nv.utils.windowResize(chart.update);

return chart;
});

Could someone explain how to make it work and - more importantly - why? Appreciate any guidance!

like image 769
mcl Avatar asked Dec 20 '12 05:12

mcl


2 Answers

I solved the problem as soon as I opened the bounty (d'oh!)

Here is what worked for me

.tickFormat(function(d){return d3.time.format('%d-%b')(new Date(d));})

and the trick was to reformat the data for nvd3 AFTER this is axis is created

like image 153
CQM Avatar answered Nov 02 '22 06:11

CQM


JavaScript timestamps are im miliseconds, so you should multiply the Unix stamp by 1000 before using it.

like image 25
mar10 Avatar answered Nov 02 '22 08:11

mar10