Created
November 9, 2015 23:02
-
-
Save pandafulmanda/0557e7dda82411ef5a5b to your computer and use it in GitHub Desktop.
fit to window size and use scales
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
<html> | |
<head> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
</head> | |
<body> | |
<svg></svg> | |
<script> | |
var sampleData = [1, 2, 3, 4, 5, 10, 6, 2, 9, 20, 54, 30]; | |
var width = window.innerWidth; | |
var height = window.innerHeight; | |
d3.select("svg") | |
.attr("width", width) | |
.attr("height", height); | |
drawBars(sampleData); | |
function drawBars(data){ | |
var y = data; | |
var x = data.map(function(dataPoint, index){ | |
return index; | |
}); | |
var xPosition = d3.scale.ordinal() | |
.domain(x) | |
.rangeRoundBands([0, width], 0.2); | |
var yHeight = d3.scale.linear() | |
.domain([0, d3.max(y)]) | |
.rangeRound([0, height]); | |
var dataColor = d3.scale.category10(x) | |
.domain(x); | |
var eachDataPoint = d3.select("svg") | |
.selectAll("rect") | |
.data(data); | |
eachDataPoint.enter() | |
.append("rect"); | |
eachDataPoint | |
.attr("x", function(dataItem, index){ | |
return xPosition(index); | |
}) | |
.attr("y", function(dataItem, index){ | |
return height - yHeight(dataItem); | |
}) | |
.attr("width", xPosition.rangeBand) | |
.attr("height", yHeight) | |
.attr("fill", function(dataItem, index){ | |
return dataColor(index); | |
}) | |
.on('mouseenter', function(dataItem, index){ | |
d3.select(this).attr("fill", "blue"); | |
}) | |
.on('mouseout', function(dataItem, index){ | |
var originalColor = dataColor(index); | |
d3.select(this).attr("fill", originalColor); | |
}); | |
eachDataPoint.exit() | |
.remove(); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment