JSFiddle - React, Tailwind, and code Playground
by ramnathv
HTML
<div id="display"></div>
CSS
.axis path,
.axis line {
fill: none;
stroke: #aaa
}
.axis text {
font-size: 10px;
font-family: 'Helvetica';
}
.chart {
float: left;
}
}
CoffeeScript
data = [{x: "A", y: 1}, {x: "B", y: 2}, {x: "C", y: 3}, {x: "D", y: 10}]
# 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) -> O.height - S.y A.y d
fill: (d, i) -> S.c(i)
exports = (selection) ->
selection.each (data) ->
d3.select(this).selectAll("rect")
.data(data).enter()
.append("rect")
.attr that.G
exports
Axis = (S, O) ->
that = this
@Ax = d3.svg.axis()
.scale(S.x)
.orient("bottom")
.tickSize(0)
exports = (selection) ->
selection.each (data) ->
d3.select(this).append("g")
.attr("class", "x axis")
.attr("transform", "translate(0, #{O.height})")
.call(that.Ax)
exports
O =
margin: {top: 20, bottom: 20, left: 32, right: 20}
width: 200
height: 100
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.1).domain data.map(A.x)
y: d3.scale.linear().range([O.height, 0]).domain [0, d3.max(data, A.y)]
c: (d, i) -> "steelblue"
divs = d3.select("#display")
.selectAll("div")
.data(d3.range(6).map((i) -> data)).enter()
.append("div")
.attr("class", "chart")
chart = divs.append("svg")
.attr({width: W, height: H})
.append("g")
.attr("transform", "translate(#{O.margin.left}, #{O.margin.top})")
myBars = BarG(S, A, O)
chart.call(myBars)
chart.selectAll("rect")
.transition()
.style("fill", (d, i) ->
if i is 0 then "darkred" else "steelblue"
)
x_axis = Axis(S, O)
chart.filter((d, i) -> i is 2).call(x_axis)