Skip to content

Instantly share code, notes, and snippets.

@ramnathv
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramnathv/58f1e63bd8137b872a97 to your computer and use it in GitHub Desktop.
Save ramnathv/58f1e63bd8137b872a97 to your computer and use it in GitHub Desktop.
Histogram using Bar
.axis line,
.axis path{
fill: none;
stroke: black
}
.axis text {
font-size: 11px;
}
{"description":"Histogram using Bar","endpoint":"","display":"svg","public":true,"require":[],"fileconfigs":{"inlet.js":{"default":true,"vim":false,"emacs":false,"fontSize":12},"inlet.coffee":{"default":true,"vim":false,"emacs":false,"fontSize":12},"_.md":{"default":true,"vim":false,"emacs":false,"fontSize":12},"config.json":{"default":true,"vim":false,"emacs":false,"fontSize":12},"app.css":{"default":true,"vim":false,"emacs":false,"fontSize":12}},"fullscreen":false,"play":false,"loop":false,"restart":false,"autoinit":true,"pause":true,"loop_type":"pingpong","bv":false,"nclones":15,"clone_opacity":0.4,"duration":3000,"ease":"linear","dt":0.01,"ajax-caching":true,"thumbnail":"http://i.imgur.com/wq6lvPO.png"}
# Reusable Bar Chart Code
# Primitives are redefined to be
# S -> Scales
# A -> Accessors
# O -> Options (width, height, margin)
BarG = (S, A, O) ->
that = this
@G =
x: (d) -> S.x A.x d
y: (d) -> S.y A.y d
width: S.x.rangeBand()
height: (d) -> S.y.range()[0] - S.y A.y d
fill: (d, i) -> S.c(i)
chart = (selection) ->
selection.each (data) ->
d3.select(this).selectAll("rect")
.data(data).enter()
.append("rect")
.attr that.G
chart
Axis = (S) ->
that = this
@xAxis = d3.svg.axis().scale(S.x).orient("bottom")
exports = (selection) ->
selection.each (data) ->
d3.select(this).append("g")
.attr("class", "x axis")
.attr("transform", "translate(0, #{S.y.range()[0]})")
.call(that.xAxis)
d3.rebind(exports, xAxis, "ticks", "tickFormat")
exports
data = [{x: "A", y: 1}, {x: "B", y: 2}, {x: "C", y: 3}, {x: "D", y: 10}]
dat = d3.range(1000).map(d3.random.normal())
data = d3.layout.histogram().bins(10)(dat)
O =
margin: {top: 20, bottom: 20, left: 32, right: 20}
width: 391
height: 170
W = O.width + O.margin.left + O.margin.right
H = O.height + O.margin.top + O.margin.bottom
A =
x: (d) -> d.x
y: (d) -> d.y
S =
x: d3.scale.ordinal().rangeRoundBands([0, O.width], 0.02).domain data.map(A.x)
y: d3.scale.linear().range([O.height, 0]).domain [0, d3.max(data, A.y)]
c: (d, i) -> "steelblue"
svg = d3.select("svg")
.attr({width: W, height: H})
.append("g")
.attr("transform", "translate(#{O.margin.left}, #{O.margin.top})")
chart = svg.datum(data)
chart.call(BarG(S, A))
chart.append("g")
.attr("transform", "translate(#{S.x.rangeBand()/2})")
.call(Axis(S).ticks(3).tickFormat(d3.format('.1f')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment