Created
November 6, 2012 17:18
-
-
Save mathiasverraes/4026123 to your computer and use it in GitHub Desktop.
D3 barchart with groups
This file contains hidden or 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> | |
<meta charset="utf-8"> | |
<title></title> | |
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> | |
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script> | |
<style> | |
svg { | |
font: 10px sans-serif; | |
shape-rendering: crispEdges; | |
} | |
rect.blue { | |
fill: blue; | |
} | |
rect.red{ | |
fill: red; | |
} | |
</style> | |
<body> | |
<script> | |
var data = [5,3,7,8,1,2] | |
var barWidth = 20; | |
var width = data.length * barWidth * 2; | |
var height = 200; | |
var x = d3.scale.linear() | |
.domain([0, data.length]) | |
.range([0, width]); | |
var y = d3.scale.linear() | |
.domain([1, 9]) | |
.range([0, height]); | |
var svg = d3.select("body").append("svg") | |
.attr("width", width ) | |
.attr("height", height) | |
var group = svg.selectAll('g') | |
.data(data) | |
.enter() | |
.append('g') | |
group | |
.append('rect') | |
.classed('blue', true) | |
.attr('x', function(d, i){return x(i)}) | |
.attr('width', barWidth) | |
.attr('y', function(d){return y(d)}) | |
.attr('height', function(d){return height-y(d)}) | |
group | |
.append('rect') | |
.classed('red', true) | |
.attr('x', function(d, i){return x(i)+20}) | |
.attr('width', barWidth) | |
.attr('y', function(d){return y(d)}) | |
.attr('height', function(d){return height-y(d)}) | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment