Getting the scale right for a line chart for a simple CSV in D3 v4

时间:2016-10-19 13:36:51

标签: javascript csv d3.js

I have the following CSV file, it is pretty simple.

I want to draw a line chart with that data. I am finding it difficult to do so with the new version of D3.

I have tried all sorts, but this is what I currently have.

var x = d3.scaleBand().range([0, width]);

Then later inside the d3.csv() call I have

x.domain(data, function(d) { return d.date; });

That doesn't work, I also tried:

var x = d3.scaleOrdinal().range([0, width]);

But that too didn't work. I find it easier working with Linear Quantitative scales.

Update

Following from Gerardo's correction (good spot by the way), I now get this:

wrong chart

1 个答案:

答案 0 :(得分:1)

In a scale, the domain has to be an array. So, this:

x.domain(data, function(d) { return d.date; });

Should be:

x.domain(data.map(function(d) { return d.date; }));

You can see the difference in these demos. First, your code:

var data = [{date: "Q1 2014", close: 58},
           {date: "Q2 2014", close: 48},
           {date: "Q3 2014", close: 67},
           {date: "Q4 2014", close: 33},
           {date: "Q1 2014", close: 27},
           {date: "Q2 2014", close: 87},
           {date: "Q3 2014", close: 23},
           {date: "Q4 2014", close: 56}];

var scale = d3.scaleOrdinal().domain(data, function(d){
  return d.date;
});
                                     
console.log(scale.domain());
<script src="https://d3js.org/d3.v4.min.js"></script>

Now, using map:

var data = [{date: "Q1 2014", close: 58},
           {date: "Q2 2014", close: 48},
           {date: "Q3 2014", close: 67},
           {date: "Q4 2014", close: 33},
           {date: "Q1 2014", close: 27},
           {date: "Q2 2014", close: 87},
           {date: "Q3 2014", close: 23},
           {date: "Q4 2014", close: 56}];

var scale = d3.scaleOrdinal().domain(data.map(function(d){
  return d.date;
}));
                                     
console.log(scale.domain());
<script src="https://d3js.org/d3.v4.min.js"></script>

EDIT: Since you are making a line chart, you should use a time scale or another scale, but not an ordinal one. The reason is that an ordinal scale expects the same number of values in the range as the number of values in the domain. That being said, you can use a scalePoint:

var x = d3.scalePoint().range([0, width])
    .domain(data.map(function(d) { return d.date; }));