Reputation:
I'm a beginner at D3 and would like to create a line graph. How would I go about doing so if my data is in 3 separate arrays?
My data would be like this, except for 365 values:
var dates = ["2013-07-11T00:00:00", "2013-07-12T00:00:00", "2013-07-15T00:00:00", "2013-07-16T00:00:00", "2013-07-17T00:00:00", "2013-07-18T00:00:00"];
var positions = [0, 0.004, 0.008, 0.012, 0.016, 0.02];
var prices = [61.041, 60.93, 61.063, 61.456, 61.473, 61.68];
The positions are a percentage estimate of the date to make graphing easier. The positions would be the x-values, and the prices would be the y-values. Then, I would like to have the x-axis show tick marks that reflect the dates (probably parsing the dates array).
I found a tutorial online, but it's for graphing circles, so I'm not sure where to begin.
Here's the tutorial: http://www.jeromecukier.net/blog/2012/05/28/manipulating-data-like-a-boss-with-d3/
Thanks in advance for your help!
Upvotes: 0
Views: 1218
Reputation: 7687
If the indices are all consistent across the arrays, you can use map
to create a single array out of all of them:
var newArray = dates.map(function(d, i){
return { 'date' : d, 'position' : positions[i], 'price' : prices[i] };
};
You can then use that array for creating your graph.
You can also use the first array as your data, and then reference the other data by position from within d3 functions, which all take both d
(the data point) and i
(the index) as inputs.
For example, in a line generator, you can say:
var line = d3.svg.line()
.x(function(d, i) { return x(positions[i]); })
.y(function(d, i) { return y(prices[i]); });
In this example, x
and y
would be scales you have defined for your positions
and prices
axes. This approach would lead to slightly messier code than the first way, and as we all know, messi did not win the world cup.
Upvotes: 2
Reputation: 169
You could use a loop to turn your multiple arrays into one array of objects looking something like:
var data = [{date: "2013-07-11T00:00:00", position: 0, prices: 61.041}, ...]
and then bind the data array to the svg path.
Also, you probably don't need the positions.
Using a d3 time scale should handle all that easily.
Upvotes: 0