New Year's Resolution for 2017: Make a D3 Block a day to teach myself D3. This is Number 4. This example tries to implement the bar chart from January 1st using SVG elements outlined in Malcolm Maclean's D3.js Tips and Tricks V4.
xxxxxxxxxx
<meta charset="utf-8">
<head>
<title>D3 Block-a-Day: Day 4, January 4, 2017</title>
<style> /* set the CSS */
body { font: 20px Helvetica Neue; background: #fff}
.rect { fill: steelblue; stroke: black; stroke-width: 1; }
.yaxis { font: 14px Helvetica Neue; }
.labels { font: 16px Helvetica Neue; fill: #fff; }
svg { background-color: #fff; }
.control-group { padding-left: 70px; padding-top: 10px; margin: 10px; }
</style>
</head>
<body>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
// set the dimensions and margins of the graph
var margin = {top: 20, right: 20, bottom: 30, left: 70},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// set the ranges
var x = d3.scaleBand()
.range([0, width])
.padding(0.1);
var y = d3.scaleLinear()
.range([height, 0]);
// append the svg object to the body of the page
// append a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// get the data
d3.csv("school_proficiency_data.csv", function(error, data) {
if (error) throw error;
// format the data
data.forEach(function(d) {
d.percent_proficient = +d.percent_proficient;
});
// Scale the range of the data in the domains
x.domain(data.map(function(d) { return d.school_name; }));
y.domain([0, d3.max(data, function(d) { return d.percent_proficient; })]);
// append the rectangles for the bar chart
svg.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("class", "rect")
.attr("x", function(d) { return x(d.school_name); })
.attr("width", x.bandwidth())
.attr("y", function(d) { return y(d.percent_proficient); })
.attr("height", function(d) { return height - y(d.percent_proficient); });
// Add vertical labels to bars
svg.selectAll("text")
.data(data)
.enter().append("text")
.attr("class", "labels")
.attr("dx", ".6em") // vertical-align: middle
.attr("dy", -30) // padding-right
.attr('transform', function(d) { return 'translate(' + x(d.school_name) + ',' + y(d.percent_proficient) + ') rotate(90)'})
.text(function(d) {return d.school_name});
// add the y Axis
svg.append("g")
.call(d3.axisLeft(y))
.attr("class", "yaxis");
// text label for the y axis
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 5 - margin.left)
.attr("x", - 0.5*height)
.attr("dy", "1em")
.style("text-anchor", "middle")
.style("font-family", "Helvetica Neue")
.text("Percent Proficient 2016");
});
</script>
</body>
https://d3js.org/d3.v4.min.js