Last active
July 12, 2018 09:36
-
-
Save vidyakesavan/2f47e612c980b23923ee59f506f434ba to your computer and use it in GitHub Desktop.
Create a basic bar chart in D3
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<title>D3: Basic Barchart</title> | |
<script type="text/javascript" src="https://d3js.org/d3.v5.js"></script> | |
<style type="text/css"> | |
/* No style rules here yet */ | |
</style> | |
</head> | |
<body> | |
<script type="text/javascript"> | |
var w = 600; | |
var h = 250; | |
var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13, | |
11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ]; | |
//create ordinal scale | |
var xScale = d3.scaleBand() | |
.domain(d3.range(dataset.length)) | |
.rangeRound([0,w]) | |
.paddingInner(0.05); | |
var yScale = d3.scaleLinear() | |
.domain([0, d3.max(dataset)]) | |
.range([0, h]); | |
//Create SVG element | |
var svg = d3.select("body") | |
.append("svg") | |
.attr("width", w) | |
.attr("height", h); | |
//build bars | |
svg.selectAll("rect") | |
.data(dataset) | |
.enter() | |
.append("rect") | |
.attr("x", function(d,i){ | |
return xScale(i); | |
}) | |
.attr("y", function(d){ | |
return h - yScale(d); | |
}) | |
.attr("width", xScale.bandwidth()) | |
.attr("height", function(d) { | |
return yScale(d); | |
}) | |
.attr("fill" ,"teal"); | |
//text labels on bars | |
svg.selectAll("text") | |
.data(dataset) | |
.enter() | |
.append("text") | |
.text(function(d) { | |
return d; | |
}) | |
.attr("x", function(d,i){ | |
return xScale(i) + xScale.bandwidth() / 2; | |
}) | |
.attr("y", function(d){ | |
return h - yScale(d) + 14 ; | |
}) | |
.attr("font-family" , "sans-serif") | |
.attr("font-size" , "11px") | |
.attr("fill" , "white") | |
.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