<html>
<head>
<script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
<link rel="stylesheet" type="text/css" href="barchart.css" />
<script src="barchart.js"></script>
</head>
<body>
<div class="chart"></div>
</body>
</html>
.chart {
width: 450px;
height: 300px;
margin: 20px;
}
.axis {
font-size: 12px;
line-height: 16px;
}
.northing line {
stroke: #F2F2F2;
}
line {
fill: none;
stroke: #727272;
}
path {
fill: none;
stroke: #727272;
}
window.onload = function () {
var margin = {top: 20, right: 0, bottom: 21, left: 30},
height = 300,
width = 400,
w = width - margin.left - margin.right,
h = height - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y-%m-%d").parse;
var dataset = [
{ date: "2017-03-23", nb_requests: 14 },
{ date: "2017-03-25", nb_requests: 10 },
{ date: "2017-04-01", nb_requests: 6 },
{ date: "2017-04-02", nb_requests: 7 },
];
dataset.forEach(function(d) {
d.date = parseDate(d.date);
});
var svg = d3.select('.chart')
.append('svg')
.attr("width", '100%')
.attr("height", '100%')
.attr("viewBox", "0 0 " + width + " " + height)
.attr("preserveAspectRatio", "xMinYMin meet")
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
var x = d3.scale.ordinal().rangeRoundBands([0, w], .2, .02);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickSize(0)
.tickPadding(5)
.tickFormat(d3.time.format("%d/%b"));
x.domain(dataset.map(function(d) { return d.date; }));
svg.append("g")
.attr("class", "axis easting")
.attr("transform", "translate(0," + h + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "middle");
var y = d3.scale.linear().range([h, 0]);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(6);
y.domain([0, d3.max(dataset, function(d) { return d.nb_requests; })]);
svg.append("g")
.attr("class", "axis northing")
.call(yAxis)
.selectAll("line")
.attr("x2", w)
svg.selectAll('rect')
.data(dataset)
.enter()
.append('rect')
.attr('width', function(d,i){
return x.rangeBand();
})
.attr('height', function(d,i){
return h - y(d.nb_requests);
})
.attr('x', function(d,i){
return x(d.date);
})
.attr('y', function(d,i){
return y(d.nb_requests);
})
.attr('fill', 'blue')
;
};