reading in real data!

So, the coolest thing about learning how to write code for the web is that every website is an example.  Today’s goal was to figure out how read in real data (in more than one way).  I found this super mysterious on Friday when I started looking into it, but knew that I was missing some core concept.  Today I dove back in, found some good references, and figured out what I was missing conceptually.

At first I was looking at this documentation, but realized I was missing something about where the data got stored.  In the past in R reading in data looks something like “data.frame = read.csv(‘wheredatais.csv’, parameters… )”.  But, in d3, it’s not about setting the variable equal to something coming out of d3.tsv/d3.csv/d3.json.  Rather, it seems to be about defining functions within the d3.csv parenthesis which includes either using the data or storing it in some variable.  I’m just figuring this out, so am likely butchering the explanation :).  But, launch & iterate, right.

They key was reading this note on stack overflow:

The principle behind d3.json() is to do everything in this function, which will be executed when the json is loaded:

var data; // a global
d3.json("path/to/file.json", function(error, json) {
  if (error) return console.warn(error);
  data = json;
  visualizeit();
});

and this on Mike Bostock’s original documentation on the more general topic of data requests:

Also, you may find it convenient to save loaded data to the global namespace, so that you can access it after the initial render, such as during a transition. You can do this using closures, or simply assign the loaded data to a global:

var data; // a global

d3.json("path/to/file.json", function(error, json) {
  if (error) return console.warn(error);
  data = json;
  visualizeit();
});

Once I understood that the function is the key, I was able to load in data.  I wanted to find data that was universally accessible.  So I found the d3.tsv call in the page source for a New York Times interactive visualization on picking players for the NFL draft.  In my browser’s console, I wrote:

var data;

d3.tsv(“http://graphics8.nytimes.com/newsgraphics/2013/04/18/nfl-draft/d9c0f4a098da672625afadfee7be4135fb0f724b

/picks.tsv”, function(error, picks) { data = picks; });

data;

And there it was – a beautiful array!  Easy peasy :).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s