Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
fit to window size and use scales
<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