rond rond - 2 months ago 30
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

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 ="svg"),
margin = {top: 20, right: 20, bottom: 30, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + + ")");

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(; })
.y(function(d) { return y(d.close); });

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

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

.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")

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

.attr("class", "line")
.attr("d", line);

I have tried creating the
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
and returns a 404.

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


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)