Getting the Data

Learn how to fetch and parse data in D3.

We'll cover the following...

We’re going to jump forward a little bit to the portion of the JavaScript code that loads the data for the graph.

I’m going to go out of the sequence of the code here because if you know what the data is that you’re using, it will make explaining some of the other functions much easier.

The code

The section that grabs the data is this bit:

Press + to interact
d3.csv("data.csv").then(function(data) {
// format the data
data.forEach(function(d) {
d.date = parseTime(d.date);
d.close = +d.close;
});

There are lots of different ways that we can get data into our web page and turn it into graphics. The method that we’ll want to use will probably depend more on the format that the data is in than the mechanism we want to use for importing.

One of the major changes made with the transition to version 5 was the change from loading data via a request to a promise.

A promise allows the complexity of JavaScript’s asynchronous function to be simplified somewhat.

Think of a normal fetch of data being an introduced delay to the smooth loading of a web page. A promise allows an object to process on the assumption that the values that it is retrieving will be available in due course. In the meantime, the code can continue to process.

Sounds tricky? I agree. I can see the advantages of the change, and it will mean smoother and faster loading. For the purposes of this course, we will be keeping things as simple as possible.

For instance, if it’s only a few points of data, we could include the information directly in the JavaScript.

That would make it look something like:

var data = [ 
  {date:"1-May-12",close:"58.13"}, 
  {date:"30-Apr-12",close:"53.98"}, 
  {date:"27-Apr-12",close:"67.00"}, 
 
...

Data formats in D3

...