Last active
December 12, 2015 08:39
-
-
Save HectorMalot/4745902 to your computer and use it in GitHub Desktop.
d3.js experiments
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> | |
<head> | |
<title>Easy Barchart | |
</title> | |
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?1.29.1"></script> | |
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.layout.js?1.29.1"></script> | |
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.time.js?1.29.1"></script> | |
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.csv.js?1.29.1"></script> | |
<style type="text/css"> | |
svg { margin: 20px 20px 20px 20px; } | |
#playground { text-align:left; } | |
</style> | |
</head> | |
<body> | |
<div id="playground"></div> | |
<script type="text/javascript"> | |
var data = [ 15 , 6, 3 , 4]; | |
var width = 600; | |
var height = 25; | |
var barPadding = 1; | |
var barHeight = height; | |
var svg = d3.select('#playground') | |
.append("svg") | |
.attr('width',width) | |
.attr('height',height); | |
var xScale = d3.scale.linear() | |
.domain([0, d3.sum(data)]) | |
.range([0,width-20]); | |
var colorScale = d3.scale.category10(); | |
svg.selectAll("rect") | |
.data(data) | |
.enter() | |
.append("rect") | |
.attr("class","bar") | |
.attr("x", function(d,i){ | |
sum = 0; | |
for(var j=0; j < i; j++){ | |
sum += data[j]; | |
} | |
return xScale(sum)+i*barPadding; | |
}) | |
.attr("y", 0) | |
.attr("width", function(d){return xScale(d);}) | |
.attr("height",barHeight) | |
.attr("fill", function(d){return colorScale(d);}); | |
svg.selectAll("text") | |
.data(data) | |
.enter() | |
.append("text") | |
.text(function(d){return d;}) | |
.attr("x", function(d,i){ | |
sum = 0; | |
for(var j=0; j < i; j++){ | |
sum += data[j]; | |
} | |
return xScale(sum)+i*barPadding+3; | |
}) | |
.attr("y",barHeight/2+3) | |
.attr("font-family", "sans-serif") | |
.attr("font-size", "11px") | |
.attr("vertical-align", "middle") | |
.attr("fill", "white"); | |
svg.append("text") | |
.text(d3.sum(data)) | |
.attr("x", xScale(d3.sum(data))+data.length+1) | |
.attr("y", barHeight/2+3) | |
.attr("font-family", "sans-serif") | |
.attr("font-size", "11px") | |
.attr("vertical-align", "middle") | |
.attr("fill", "black"); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment