Thursday, February 23, 2012

First D3 Graphic

OK, my first D3 visualization, or at least a screenshot of the core data part of it, is above. Of course I have to add scales, explanation, etc., but I'm pretty happy with my progress today. You can click on the image to expand. Consider this a proof of concept (where the concept is I'm enough of a programmer to understand D3).

This is the percent of students receiving free (not reduced) lunch data by school in each school in Rhode Island from the NCES's Common Core of Data for the most recent (2009-2010) school year. Providence Public School District schools are in red, charters in green, others in blue. Each line is a school.

Hmm... I wonder where the lowest performing 5% of schools are going to be just about every year...

So... if you're curious, here's the code:

var barWidth = 3;
var width = 1200
var height = 600

var xScale = d3.scale.linear().domain([0, 321]).range([0, width]);
var yScale = d3.scale.linear().domain([0, 1]).range([0, 600]);

console.log(xScale(150));

var chart = d3.select("body").append("div")
.attr("class", "chart")
.append("svg:svg")
.attr("width", width)
.attr("height", height);

function cleanup(element, index, array)
{
element.FREE_LUNCH = parseInt(element.FREE_LUNCH);
element.PCT_FREE_LUNCH = element.FREE_LUNCH / element.TOTAL_STUDENTS
return element
}

function sort_by_fl(a, b)
{
if (a.PCT_FREE_LUNCH < b.PCT_FREE_LUNCH)
return -1;
if (a.PCT_FREE_LUNCH > b.PCT_FREE_LUNCH)
return 1;
return 0;
}

function colorize(school)
{
if (school.DISTRICT_ID == "4400900")
return "red";
if (school.CHARTER == "Yes")
return "green";
return "blue";
}

d3.csv('./frl.csv', function(csv)
{
var schools = csv.map(cleanup)
.sort(sort_by_fl)
.reverse()

chart.selectAll("rect")
.data(schools)
.enter()
.append("svg:rect")
.attr("x", function(datum, index) { return xScale(index); })
.attr("y", function(datum) { return height - yScale(datum.PCT_FREE_LUNCH); })
.attr("height", function(datum) { return yScale(datum.PCT_FREE_LUNCH); })
.attr("width", barWidth)
.attr("fill", function(datum) {return colorize(datum); });
});

No comments: