simple reusable barchart with reload
attempting to add days of week as labels
by johnwun
HTML
<script src="http://d3js.org/d3.v2.js"></script>
<p id="p1">
<p id="p2">
CSS
body {
font: 10px sans-serif;
}
#p1 svg:last-child{
border:1px solid red;
}
.axis line, .axis path {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
rect{
stroke:#0f0;
}
.bar {
fill: #bbf;
fill-opacity:0.5;
}
.y.axis g{
display:none;
}
JavaScript
function simpleBarChart() {
var width = 220, // default width
height = 60, // default height
x= d3.scale.ordinal()
.rangeRoundBands([0, width], .1),
y= d3.scale.linear()
.range([height, 0]),
defaultMargin = 5,
margin = {left:defaultMargin,right:defaultMargin,top:defaultMargin,bottom:defaultMargin+15},
xAxis= d3.svg.axis()
.scale(x)
.orient("bottom"),
yAxis= d3.svg.axis()
.scale(y)
.orient("left")
.tickSize(0),
svg=null,
xaxis,
yaxis;
function my(selection) {
selection.each(function(d, i) {
// `d` is the data and `this` is the element
// using `width` and `height`
if (svg == null)
{svg = d3.select(this).append("svg");
x.domain(d.map(function(d) { return d.day; }));
y.domain([0, d3.max(d, function(d) { return d.value; })]);
xaxis = svg.append("g")
.attr("class", "x axis");
yaxis = svg.append("g")
.attr("class", "y axis");
}
xaxis.call(xAxis).attr("transform", "translate(0," + height + ")")
;
yaxis.call(yAxis);
svg
.attr('class','none')
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d.forEach(function(_d) {
_d.value = +_d.value;
});
console.log('this should be the dataset');
console.log(d);
var bar = svg.selectAll(".bar")
.data(d)
.enter()
.append("rect")
bar.attr("width",1)
.attr("class", "bar")
...