Am trying to dynamically produce line charts depending on the JSON data inputted:
Here's my JS code:
d3.json("../js/sample2.json", function(data) {
var dataArray = new Array(), k = 0, j = 0, dataArraySize = 0, line, positionNumber,
canvas = d3.select("body").append("svg")
.attr("width", 1000)
.attr("height", 1000)
.attr("border", "black")
heightScale = d3.scale.linear()
.domain([0, 250])
.range([300, 0]);
widthScale = d3.scale.linear()
.domain([0, 200])
.range([0, 700]);
Yaxis = d3.svg.axis()
.ticks(5)
.scale(heightScale)
.orient("left");
Xaxis = d3.svg.axis()
.ticks(10)
.scale(widthScale)
.orient("bottom");
jsonLength = Object.keys(data).length;
group = canvas.append("g")
.attr("class", "grp")
.attr("transform", "translate(100,10)");
// Conversion of JSON data to appropriate data format
for (j = 0; j < jsonLength; j += 2) {
var innerObjArray = new Array();
positionNumber = Object.keys(data[j].position).length;
for (k = 0; k < positionNumber; k++) {
var obj = {};
obj.x = data[j].position[k];
obj.y = data[j + 1].position[k];
innerObjArray.push(obj);
}
dataArray.push(innerObjArray);
}
console.log(dataArray);
dataArraySize = dataArray.length;
//Graphical representation of the dataArray
line = d3.svg.line()
.x(function(d) {
return d.x;
})
.y(function(d) {
return d.y;
});
for (k = 0; k < dataArraySize; k++) {
d3.select(".grp")
.append("path")
.attr("d", line(dataArray[k]))
// .attr("transform", "translate(100,10)")
.attr("fill", "none")
.attr("stroke", "hsl(" + Math.random() * 360 + ",50%,50%)")
.attr("stroke-width", 3);
console.log(dataArray[k]);
}
group.append("g")
.attr("transform", "translate(0, 300 )")
.call(Xaxis)
group.append("g")
.call(Yaxis)
.attr("transform", "translate(0,0)");
});
I have given
heightScale = d3.scale.linear()
.domain([0, 250])
.range([300, 0]);
Which i thought would work,but it didnt.
Here's my JSON data:
[{"name": "x1",
"position":[0,60,80,100,200]
},
{"name": "y1",
"position":[0,190,220,160,240]
},
{"name": "x2",
"position":[0,60,80,100,200]
},
{"name": "y2",
"position":[10,90,20,60,40]},
{"name": "x3",
"position":[30,50,70,90,150]
},
{"name": "y3",
"position":[20,160,170,160,150]}]
This is currently my output
Right now the chart is starting from the (200,240) position..
The chart is currently inverted as i have started the line at (0,0) ending at (200,240) for the 1st line and so forth..(Inputted through the JSON data)