D3 Histograms
by yairamon
HTML
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="//rawgit.com/Caged/d3-tip/master/index.js"></script>
<link rel="stylesheet" href="//rawgit.com/Caged/d3-tip/master/examples/example-styles.css">
<div id="chart"></div>
CSS
.axis line,
.axis path {
fill: none;
stroke: #ddd;
shape-rendering: crispEdges;
}
.axis text {
font-size: 11px;
fill: #bbb;
font-family: "Helvetica";
}
.y.axis path {
display: none;
}
.d3-tip {
font-weight: normal;
padding: 5px;
}
.d3-tip p{
margin: 0px;
}
CoffeeScript
data = [{"x":40,"y":41},{"x":36,"y":23},{"x":37,"y":20},{"x":39,"y":16},{"x":34,"y":12},{"x":32,"y":10},{"x":35,"y":9},{"x":33,"y":9},{"x":38,"y":9},{"x":30,"y":6},{"x":26,"y":4},{"x":31,"y":3},{"x":27,"y":2},{"x":28,"y":1},]
o =
width: 400
height: 200
margin: {top: 60, bottom: 20, left: 40, right: 20}
o.W = o.width + o.margin.left + o.margin.right
o.H = o.height + o.margin.top + o.margin.bottom
svg = d3.select("#chart")
.append("svg")
.attr
width: o.W
height: o.H
.append("g")
.attr
transform: "translate(#{o.margin.left}, #{o.margin.top})"
S =
x: d3.scale.linear().range([0, o.width])
y: d3.scale.linear().range([o.height, 0])
A =
x: (d) -> d.x
y: (d) -> d.y
S.x.domain [25, 40]
S.y.domain [0, d3.max(data, A.y)]
rect = svg.selectAll("rect")
.data(data)
xAxis = d3.svg.axis()
.orient('bottom')
.scale(S.x)
svg.append("g")
.attr
class: "x axis"
transform: "translate(0, #{o.height})"
.call(xAxis)
yAxis = d3.svg.axis()
.orient("left")
.scale(S.y)
.ticks(6)
.tickSize(-o.width)
svg.append("g")
.attr
class: "y axis"
.call(yAxis)
rect.enter().append("rect")
.attr
x: (d) -> S.x A.x(d)
y: (d) -> S.y A.y(d)
width: o.width/(data.length + 2) - 1
fill: "steelblue"
.transition().duration(750)
.attr
height: (d) -> S.y(0) - S.y(A.y(d))
dx = A.x(data[1]) - A.x(data[0])
tip = d3.tip()
.attr('class', 'd3-tip')
.html (d) ->
"""
<p style="text-align:center;line-height:1.5em;">
#{d.x} to #{d.x + dx}<br/>
#{d.y} instances
</p>
"""
svg.call(tip)
rect.on "mouseover", tip.show
rect.on "mouseout", tip.hide