Skip to content

Instantly share code, notes, and snippets.

@achillesp
Last active November 8, 2022 16:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save achillesp/2aa9592d4c069e3afd74d8f09769ca37 to your computer and use it in GitHub Desktop.
Save achillesp/2aa9592d4c069e3afd74d8f09769ca37 to your computer and use it in GitHub Desktop.
barchart using d3 with scale and axes
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Bar Chart</title>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style>
.bar:hover {
fill: cyan;
}
.bar {
fill: steelblue;
}
.axis text {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
/*display: none;*/
}
</style>
</head>
<body>
<h1>Bar Chart using D3.js</h1>
<svg class="bar-chart"></svg>
<script>
var dataset = [120, 30, 23, 123, 134, 233, 183, 78, 382, 88,201];
var w = 800, h = 500;
var margin = {top: 20, right: 30, bottom: 30, left: 40},
svgWidth = w - margin.left - margin.right,
svgHeight = h - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.domain(d3.range(0, dataset.length))
.rangeRoundBands([0, svgWidth], 0.1, 0.2);
var y = d3.scale.linear()
.domain([0, d3.max(dataset)])
.range([svgHeight, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var barChart = d3.select('svg')
.attr("width", w)
.attr("height", h)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
barChart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + svgHeight + ")")
.call(xAxis);
barChart.append("g")
.attr("class", "y axis")
.call(yAxis);
barChart.selectAll(".bar")
.data(dataset)
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", function(d, i) {
return x(i);
})
.attr("y", function(d, i) {
return y(d);
})
.attr("width", x.rangeBand())
.attr("height", function(d, i) {
return svgHeight - y(d);
})
.append('title')
.text(function(d) {
return d;
});
barChart.selectAll(".value")
.data(dataset)
.enter()
.append("text")
.text(function(d) {
return d;
})
.attr("x", function(d, i) {
return x(i) + x.rangeBand() / 2;
})
.attr("y", function(d, i) {
return y(d) - 5;
})
.attr("class", "value")
.attr("text-anchor", "middle");
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment