user2670815 user2670815 - 4 months ago 283
JSON Question

Using techanJS D3 examples with JSON data

I what to use a couple of the techanJS examples in my application but am struggling use my own data.

Here is the example code for the close chart which I want to use.

I have a play! framework application which passes in a List[CloseList] array, this is then converted to a JSON object using:

var closesJSON = @{Html(new Gson().toJson(closes))};


I am then assuming that I will be able to replace d3.csv() with d3.json() but cannot find a working example and my hacking hasn't got me anywhere so far.

d3.csv("data.csv", function(error, data) {
var accessor = close.accessor();

data = data.slice(0, 200).map(function(d) {
return {
date: parseDate(d.Date),
open: +d.Open,
high: +d.High,
low: +d.Low,
close: +d.Close,
volume: +d.Volume
};
}).sort(function(a, b) { return d3.ascending(accessor.d(a), accessor.d(b)); });

x.domain(data.map(accessor.d));
y.domain(techan.scale.plot.ohlc(data, accessor).domain());

svg.append("g")
.datum(data)
.attr("class", "close")
.call(close);

svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);

svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Price ($)");
});


Working code here, this renders:

d3.json("/api/closedata/@equity.getId", function(error, data) {
var accessor = close.accessor();

data = data.map(function(d,i) {
console.log(d.high);
return {
date : parseDate(d.closeDate),
open : d.openPrice,
high : d.high,
low : d.low,
close : d.closePrice,
volume : d.volume
}
}).sort(function(a, b) { return d3.ascending(accessor.d(a), accessor.d(b)); });


x.domain(data.map(accessor.d));
y.domain(techan.scale.plot.ohlc(data, accessor).domain());

svg.append("g")
.datum(data)
.attr("class", "close")
.call(close);

svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);

svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Price ($)");
});

Answer

I you can stock your data in a json file, you have just to use the function

d3.json("file.json",callback);

after, you have to change the name of the attributes in the code (the attirbutes on his csv are probably differents to your attributes in json)

callback, is usually a function but i don't think you have any other change to do in your code.

Verify your json (use a website like http://jsonprettyprint.com/), test the code on your computer (http://bl.ocks.org/andredumas/af8674d57980790137a0) with the default csv to see if it's work. It it's work, change to use json (like i told you).

Comments