D3 graph from csv

Getting Data Outside D3 or Plotly CSV Functions

Please follow and like us:

D3 and plotly.js are two of the main graphing tools for web applications. They can get data from JSON strings or files, CSV files, or TSV files. However, one problem that was very difficult to overcome is the fact that JavaScript sometimes runs asynchronously.

The standard d3 function goes something like this:

d3.json('csvfile.csv', function(data){
//do something with data
});

Other iterations of this function use promises such as then or await. I won’t cover that in this article.

Getting data outside of the D3.json function in another function is quite tricky. Many books will tell you to keep all of the D3 function calls that require this data inside this function. The more complex your app’s structure, the harder this gets.

Like D3, Plotly, which was made using d3, produces asynchronous functions. Asynchronous means that that the code does not necessarily go in order from one line to the next. So passing data and variables from asynchronous functions to synchronous functions can be very tricky.

I ran across a simple, one-line workaround that is especially useful if you want to pass the data from Plotly.d3.csv, d3.csv, Plotly.d3.json, and other asynchronous data functions into synchronous functions.

First of all, let me point out that there are other ways of doing this, and I am by no means saying that this is the best way. It works, though.

window.data=data;

This line sets a global variable equal to a local variable. It has to be in this order and not the other way around for it to work. If you try it saying data =window.data, it will not work. Then you find that window.data is undefined.

So instead of referring to the variable data in outside functions, use window.data.

Technically, window is an object that has already been created. Window.data references a variable of the window object.

Usually, if a variable is first defined within synchronous functions, making it global just means putting “window.” before the name when using in another function. However, when a variable is first created in an asynchronous function, this is not automatic, and you must make the window.variable = to the variable.

Other methods of getting around synchronous vs. asynchronous data involve somewhat complex callback schemes, or they involve object instantiation with embedded function calls. While this will work, what you really want to do is to pass data or variables from one function to another. So, setting:

window.variablename = variablename;

is my favorite solution.

Please follow and like us: