rond rond - 1 month ago 16
Javascript Question

Phoenix: How to load a static tsv file for d3 graph

I am working on a web app powered by Phoenix framework. I am trying to get a simple d3 line graph working, but somehow d3 cannot find the static

data.tsv
file I am trying to load into the JS file to draw the graph. Is there a specific way this is supposed to be done using Phoenix Elixir?

(function LineGraph() {

var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 30, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var parseTime = d3.timeParse("%d-%b-%y");

var x = d3.scaleTime()
.rangeRound([0, width]);

var y = d3.scaleLinear()
.rangeRound([height, 0]);

var line = d3.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });

d3.tsv("../data/data.tsv", function(d) {
d.date = parseTime(d.date);
d.close = +d.close;
return d;
}, function(error, data) {
if (error) throw error;

x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.close; }));

g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));

g.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(y))
.append("text")
.attr("fill", "#000")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.style("text-anchor", "end")
.text("Price ($)");

g.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
});
})();


I have tried creating the
data.tsv
file within the js directory, the data directory and also outside the web directory of the app.

Everytime I load the app, it tries to make an XHR request to the
data.tsv
and returns a 404.

How can I load the static file to draw the graph?

Answer

Such static files are usually stored in priv/static. One way to do this would be to put data.tsv in priv/static/data/data.tsv, and then adding data to the list of directories that Plug.Static should serve, by changing lib/my_app/endpoint.txt like this:

   plug Plug.Static,
     at: "/", from: :my_app, gzip: false,
-    only: ~w(css fonts images js favicon.ico robots.txt)
+    only: ~w(css fonts images js favicon.ico robots.txt data)
Comments