[ Launch: Reusable Bars ] 8557c878d99674f5182f by ramnathv
-
-
Save ramnathv/8557c878d99674f5182f to your computer and use it in GitHub Desktop.
Reusable Bars
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
{"description":"Reusable Bars","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}},"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} |
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
d3.viz = {} | |
# Reusable Bar Chart Code | |
# Primitives are redefined to be | |
# S -> Scales | |
# A -> Accessors | |
# O -> Options (width, height, margin) | |
d3.viz.bar = (S, A) -> | |
that = this | |
dat = (d) -> d | |
@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) -> | |
g = d3.select(this).selectAll("g").data(dat) | |
gEnter = g.enter().append("g").attr("class", "bars") | |
d3.select(this).selectAll("rect") | |
.data(dat).enter() | |
.append("rect") | |
.attr that.G | |
chart.dat = (_) -> | |
return _ if arguments.length is 0 | |
dat = _; chart | |
chart | |
data = [ | |
{x: "India", y: 2}, | |
{x: "China", y: 10}, | |
{x: "Australia", y: 5}, | |
{x: "USA", y: 9} | |
] | |
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}) | |
chart = svg.append("g") | |
.attr("id", "chart") | |
.attr("transform", "translate(#{O.margin.left}, #{O.margin.top})") | |
mybar = d3.viz.bar(S, A) | |
chart.data([data]).call(mybar) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment