tl;dr How do I import d3.js data directly from other javascript vars instead of from a file?
Long version:
This question was asked in two other places here and here, but the answers were rather... lackluster, so I thought I'd ask the question a bit more specifically.
I am trying to create a chart with d3.js for the first time, but I need to load the data in from other javascript variables (arrays, specifically), not from an external file like below. I'm using javascript inside of a rails 4 app.
I want to convert this:
d3.csv("sp500.csv", type, function(error, data) {
x.domain(d3.extent(data.map(function(d) { return d.date; })));
y.domain([0, d3.max(data.map(function(d) { return d.price; }))]);
x2.domain(x.domain());
y2.domain(y.domain());
focus.append("path")
.datum(data)
.attr("class", "area")
.attr("d", area);
focus.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
focus.append("g")
.attr("class", "y axis")
.call(yAxis);
context.append("path")
.datum(data)
.attr("class", "area")
.attr("d", area2);
context.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height2 + ")")
.call(xAxis2);
context.append("g")
.attr("class", "x brush")
.call(brush)
.selectAll("rect")
.attr("y", -6)
.attr("height", height2 + 7);
});
into something that loads the data directly from a javascript variable I have already set, something like this:
var data = [];
for (i = 0; i < Math.round(totaltime / interval); i++)
{
data[i] = {
"x": i,
"y": reactionratebyinterval[i]
};
}
But all of my attempts keep failing, as I don't think I'm quite understanding what exactly changes when you aren't importing from a file. And every example I can find is one of only two types - either the data is directly entered into the graph in the code, such as:
var lineData = [{
'x': 1,
'y': 5
}, {
'x': 20,
'y': 20
}, {
'x': 40,
'y': 10
}, {
'x': 60,
'y': 40
}, {
'x': 80,
'y': 5
}, {
'x': 100,
'y': 60
}];
Or it uses the code I had above, where it imports it from a file of some sort. I need to import it from other variables though, that may change in size and content at any time. How would I do so?