Below is a snippet of JSON data that I successfully plotted on a d3js graph, using it as the x and y axis:
var data = [
{
"count": "202",
"year": "1590"
},
{
"count": "215",
"year": "1592"
},
{
"count": "179",
"year": "1593"
}
];
Now, I am facing a challenge in plotting the following JSON:
var data = {
"count": [202, 215, 179],
"year": [1590, 1592, 1593]
};
Here is the code I used to plot the axes for the initial JSON data:
/******Sample JSON data being plotted********/
var data1 = {
"count": [202, 215, 179],
"year": [1590, 1592, 1593]
};
var data = [
{
"count": "202",
"year": "1590"
},
{
"count": "215",
"year": "1592"
},
{
"count": "179",
"year": "1593"
}
];
/*************************************************/
/*******************Actual Implementation begins here*******************/
var vis = d3.select("#visualisation"),
WIDTH = 600,
HEIGHT = 400,
MARGINS = {
top: 20,
right: 20,
bottom: 20,
left: 50
},
xRange = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([d3.min(data, function (d) {
return (parseInt(d.year, 10) - 5);
}),
d3.max(data, function (d) {
return parseInt(d.year, 10);
})]),
yRange = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([d3.min(data, function (d) {
return (parseInt(d.count, 10) - 5);
}),
d3.max(data, function (d) {
return parseInt(d.count, 10);
})]),
xAxis = d3.svg.axis() // generate an axis
.scale(xRange) // set the range of the axis
.tickSize(5) // height of the ticks
.tickSubdivide(true), // display ticks between text labels
yAxis = d3.svg.axis() // generate an axis
.scale(yRange) // set the range of the axis
.tickSize(5) // width of the ticks
.orient("left") // position text labels on the left
.tickSubdivide(true); // display ticks between text labels
function initialize() {
vis.append("svg:g") // add a container for the axis
.attr("class", "x axis") // add classes to style it
.attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")") // move it into position
.call(xAxis); // add the axis to the visualization
vis.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(" + (MARGINS.left) + ",0)")
.call(yAxis);
}
initialize();
Check out the demonstration on jsfiddle here