Last active
August 29, 2015 14:23
-
-
Save nivas8292/85d299ab3116566a90ff to your computer and use it in GitHub Desktop.
Reusable Bar Chart
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> | |
<title>Reusable Bar Chart</title> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script> | |
<style> | |
section { | |
width: 400px; | |
display: inline-block; | |
max-width: 40%; | |
padding: 4%; | |
} | |
</style> | |
</head> | |
<body> | |
<section id="graph1"></section> | |
<section id="graph2"></section> | |
<script> | |
var data1 = [ | |
{x: 1, y: 20}, | |
{x: 2, y: 23}, | |
{x: 3, y: 25}, | |
{x: 4, y: 10}, | |
]; | |
var data2 = [ | |
{x: 1, y: 10}, | |
{x: 2, y: 7}, | |
{x: 3, y: 14}, | |
{x: 4, y: 19}, | |
]; | |
var bc = chart(); | |
bc.height(200) | |
.colorScale(d3.scale.category20()); | |
d3.select('#graph1') | |
.datum(data1) | |
.call(bc); | |
d3.select('#graph2') | |
.datum(data2) | |
.call(bc.colorScale(d3.scale.category10())); | |
function chart() { | |
var width = 300; | |
var height = 200; | |
var colorScale = d3.scale.category10(); | |
function barChart(selection) { | |
var dataset = this.data()[0]; | |
var xScale = d3.scale.ordinal() | |
.domain(dataset.map(function (d) { | |
return d.x; | |
})) | |
.rangeBands([0, width]); | |
var yScale = d3.scale.linear() | |
.domain([0, d3.max(dataset, function (d) { | |
return d.y; | |
})]) | |
.range([height, 0]); | |
var svg = this.append('svg').attr('width', width) | |
.attr('height', height); | |
var bars = svg.selectAll('.bar') | |
.data(dataset, function (d) { | |
return d.x | |
}); | |
//enter | |
bars.enter() | |
.append('rect') | |
.classed('bar', true); | |
//update | |
bars.attr("x", function (d, i) { | |
return xScale(d.x); | |
}) | |
.attr("y", function (d, i) { | |
return yScale(d.y); | |
}) | |
.attr("width", xScale.rangeBand()) | |
.attr("height", function (d, i) { | |
return height - yScale(d.y) | |
}) | |
.style("fill", function (d, i) { | |
return colorScale(d.x) | |
}); | |
//exit | |
bars.exit() | |
.remove(); | |
} | |
barChart.width = function (value) { | |
if (!arguments.length) | |
return width; | |
width = value; | |
return this; | |
}; | |
barChart.height = function (value) { | |
if (!arguments.length) | |
return height; | |
height = value; | |
return this; | |
}; | |
barChart.colorScale = function (value) { | |
if (!arguments.length) | |
return colorScale; | |
colorScale = value; | |
return this; | |
}; | |
return barChart; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment