Reputation: 1128
How can I display my bar graph in d3 to show a summary of how much award $ each borough is receiving using this type of data format?:
{
School: "PS 1",
Borough: Q,
Award: 1000
},
{
School: "PS 2",
Borough: Q,
Award: 3000
},
School: "PS 4",
Borough: X,
Award: 3000
}
At the moment, my bar graph is organized by X: name of school, and Y: Award $. But I want to be able to show award $ based on each borough.
Snippet:
var manhattanList = [];
var queensList = [];
var brooklynList = [];
var statenIsList = [];
var bronxList = [];
for (i=0; i<data.length; i++) {
if (data[i].boro === "M") {
manhattanList.push(data[i])
} else if (data[i].boro == "Q") {
queensList.push(data[i])
} else if (data[i].boro == "X") {
bronxList.push(data[i])
} else if (data[i].boro == "R") {
statenIsList.push(data[i])
} else {
brooklynList.push(data[i])
}
};
var width = 1000;
var height = 10000;
// creating scales:
var widthScaled = d3.scale.linear()
.domain([0, 83300000]) // data space
.range([0, width]); // pixel space
var colorScale = d3.scale.linear()
.domain([0, 83300000])
.range(["red", "blue"]);
// creating an axis - using our width scale
var axis = d3.svg.axis()
.ticks(10) // specifying how many "ticks" you want in your x
.scale(widthScaled); // scalling your x axis by canvas size
var canvas = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(100, 100)")
.call(axis);
canvas.selectAll("rect")
.data(data)
.enter()
.append("rect") // append rect for each data element
.attr("width", function(d) { return widthScaled(+d.award); })
.attr("height", 48)
.attr("y", function(d, i) { return i * 50; })
.attr("fill", function(d) { // randomizing bar colors
return "hsl(" + Math.random() * 360 + ",60%,80%)"
});
canvas.selectAll("text")
.data(data)
.enter()
.append("text")
.attr("fill", "white")
.attr("y", function(d, i) { return i * 50 + 24; }) // where the text is placed
.text(function (d) { return d.name; })
});
Here's my JSBIN: https://jsbin.com/hiruci/edit?html,output
Upvotes: 4
Views: 177
Reputation: 91
To map your data by Borough, you can use d3.nest as follows. It's a handy method that allows you to turn your data into the hierarchy you need.
d3.json("https://data.cityofnewyork.us/resource/8586-3zfm.json", ready);
function ready(error, data){
if ( error ) {
console.warn("ERROR: " + error);
}
var dataFormatted = d3.nest()
.key(function(d) { return d.boro; })
.map(data);
console.log(data);
console.log(dataFormatted);
}
Upvotes: 1