Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

X scale function in D3.js keeps returning undefined

I am new to D3.js and trying to make a bar chart with GDP on Y axis and date on X axis.

I am trying to make a xScale with d3.timeScale() but for some reason the code keeps returning undefined when using it. Below is my code, what am I doing wrong?

var data = [
  [
    "2011-01-01",
    15238.4 ]
  , 
    ["2015-07-01",
    18064.7
  ]
];

var w = 1000;
var h = 300;
var barPadding = 1;

var svg = d3.select("#chart")
            .append("svg")
            .attr("height", h);

var maxDate = d3.max(data, function(d){

  return d[0];

});

var minDate = d3.min(data, function(d){

  return d[0];

});

var maxGDP = d3.max(data, function(d){

  return d[1];

});

var minGDP = d3.min(data, function(d){

  return d[1];

});


minDate = new Date(minDate);

maxDate = new Date(maxDate)

var xScale = d3.scaleTime()
                     .domain([minDate, maxDate])
                     .range(0,w)

var yScale = d3.scaleLinear()
                     .domain([minGDP, maxGDP])
                     .range(0,h)

            .attr("width", w)

var bars = svg.selectAll("rect")
              .data(data)
              .enter()
              .append("rect")

var barAttributes = bars
                       .attr("x", function(d) { return xScale(d[0]);})
                       .attr("y", function(d) { return h - (d[1]/100);})
                       .attr("width", function(d,i) { return w/data.length;})
                       .attr("height", function(d) { return (d[1]/100) *4 ;})
                       .attr("fill", "#8e44ad");     
like image 587
chemook78 Avatar asked Dec 24 '22 21:12

chemook78


1 Answers

In D3, both domain and range have to be an array:

If domain is specified, sets the scale’s domain to the specified array of numbers.

And also:

If range is specified, sets the scale’s range to the specified array of values.

Thus, instead of:

var xScale = d3.scaleTime()
    .domain([minDate, maxDate])
    .range(0,w);

It should be:

var xScale = d3.scaleTime()
    .domain([minDate, maxDate])
    .range([0,w]);//an array here
like image 119
Gerardo Furtado Avatar answered Dec 26 '22 12:12

Gerardo Furtado