draw a histogram for discrete-type data.
Created
January 11, 2014 16:15
-
-
Save shotahorii/8372854 to your computer and use it in GitHub Desktop.
Histogram2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
.axis path, .axis line { | |
fill: none; | |
stroke: black; | |
shape-rendering: crispEdges; | |
} | |
.axis text { | |
fill: black; | |
font-size: 12px; | |
} | |
.bar { | |
fill: darkcyan; | |
} | |
</style> | |
<body> | |
<script src="http://d3js.org/d3.v3.js"></script> | |
<script> | |
var margin = 70; | |
var w = 700-2*margin; | |
var h = 500-2*margin; | |
var svg = d3.select('body') | |
.append("svg") | |
.attr({ | |
width:w+2*margin, | |
height:h+2*margin | |
}) | |
.append("g") | |
.attr("transform", "translate("+margin+","+margin+")"); | |
//scales | |
var xScale = d3.scale.ordinal() | |
.rangeRoundBands([0, w], .1); | |
var yScale = d3.scale.linear() | |
.range([h, 0]); | |
//create axises. | |
var xAxis = d3.svg.axis() | |
.scale(xScale) | |
.orient("bottom"); | |
var yAxis = d3.svg.axis() | |
.scale(yScale) | |
.orient("left"); | |
//Asynchronised. This returns immediately. | |
d3.csv("sample.csv") | |
.row(function(d){return {class: d.class, count: +d.count};}) | |
.get(function(error, rows){ | |
//set domains of the scales. | |
xScale.domain(rows.map(function(d){return d.class;})); | |
yScale.domain([0, d3.max(rows, function(d){return d.count;})]).nice(); | |
//draw x axis | |
svg.append("g") | |
.attr({ | |
class: "x axis", | |
transform: "translate(0,"+h+")" | |
}) | |
.call(xAxis) | |
.selectAll("text") | |
.style("text-anchor", "end") | |
.attr({ | |
transform: "rotate(-65, -3, 12)" | |
}); | |
//draw y axis | |
svg.append("g") | |
.attr("class", "y axis") | |
.call(yAxis) | |
.append("text") | |
.attr({ | |
y: 5, | |
x: 50 | |
}) | |
.style("text-anchor", "end") | |
.text("students"); | |
//draw bars. | |
svg.selectAll(".bar") | |
.data(rows) | |
.enter() | |
.append("rect") | |
.attr({ | |
class: "bar", | |
x: function(d){return xScale(d.class);}, | |
width: xScale.rangeBand(), | |
y: function(d){return yScale(d.count);}, | |
height: function(d){return h-yScale(d.count);} | |
}) | |
.style("stroke", "white"); | |
}); | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class | count | |
---|---|---|
0-10 | 2 | |
10-20 | 1 | |
20-30 | 7 | |
30-40 | 9 | |
40-50 | 15 | |
50-60 | 23 | |
60-70 | 20 | |
70-80 | 13 | |
80-90 | 6 | |
90-100 | 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment