Created
November 15, 2014 16:52
-
-
Save internetsadboy/2054dda3078e17eaebb8 to your computer and use it in GitHub Desktop.
d3: scalable bar chart
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"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<meta name="description" content="Scalable Bar Chart Example"> | |
<meta name="author" content="Jared Halpert"> | |
<title>Scalable Bar Chart</title> | |
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.13/d3.js"> | |
</script> | |
<style> | |
body { | |
padding-top: 50px; | |
padding-left: 100px; | |
} | |
#chartArea { | |
width: 400px; | |
height: 300px; | |
background-color: #ccc; | |
} | |
.bar { | |
display: inline-block; | |
width: 20px; | |
margin-right: 2px; | |
fill: teal; | |
} | |
</style> | |
</head> | |
<body> | |
<!-- Scalable Bar Chart --> | |
<main id="chartArea"> | |
</main> | |
<!-- Scalable Bar Chart Logic --> | |
<script type="text/javascript"> | |
var datum, width, height, SVG, yScale; | |
// arbitrary data set | |
datum = [5, 10, 15, 20, 50, 47, 23, 18, 1]; | |
// svg dimensions | |
width = 400; | |
height = 300; | |
// create svg root node | |
SVG = d3.select("#chartArea") | |
.append("svg") | |
.attr("width", width) | |
.attr("height", height); | |
// linear scaling | |
yScale = d3.scale | |
.linear() | |
.domain([0, 50]) | |
.range([0, height]); | |
// create bar chart | |
SVG.selectAll("rect") | |
.data(datum) | |
.enter() | |
.append("rect") | |
.attr("class", "bar") | |
.attr("x", function (d, i) { | |
return i * 22; | |
}) | |
.attr("y", function (d) { | |
return height - yScale(d); | |
}) | |
.attr("width", 20) | |
.attr("height", function (d) { | |
return yScale(d); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment