Skip to content

Instantly share code, notes, and snippets.

@caravinden
Last active December 19, 2018 11:07
Show Gist options
  • Save caravinden/d48b6e81404655d2e6666511abc00ecb to your computer and use it in GitHub Desktop.
Save caravinden/d48b6e81404655d2e6666511abc00ecb to your computer and use it in GitHub Desktop.
OOP approach in d3.v4
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.bar {
fill: #74BBFB;
}
</style>
<body>
<div id="barChart"></div>
</body>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var initBarGraph = {
xScale: '',
yScale: '',
svg: '',
margin: '',
xaxisDomain: '',
yMax: '',
draw: function(config) {
data = config.data,
domEle = config.element,
margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 660 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
xaxisDomain = data.map(function(d) { return d.name; });
yMax = d3.max(data, function(d) { return d.mark; });
xScale = d3.scaleBand()
.domain(xaxisDomain)
.range([0, width])
.padding(0.1)
yScale = d3.scaleLinear()
.domain([0, yMax])
.range([height, 0])
svg = d3.select("#"+domEle).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(xScale));
svg.append("g")
.call(d3.axisLeft(yScale));
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return xScale(d.name); })
.attr("width", xScale.bandwidth())
.attr("y", function(d) { return yScale(d.mark); })
.attr("height", function(d) { return height - yScale(d.mark); });
}
}
var dataSet = [{"name":"Bob","mark":33},{"name":"Robin","mark":12},{"name":"Anne","mark":41},{"name":"Mark","mark":16},{"name":"Joe","mark":59},{"name":"Eve","mark":38},{"name":"Karen","mark":21},{"name":"Kirsty","mark":25},{"name":"Chris","mark":30},{"name":"Lisa","mark":47},{"name":"Tom","mark":5},{"name":"Stacy","mark":20},{"name":"Charles","mark":13},{"name":"Mary","mark":29}];
initBarGraph.draw({
data: dataSet,
element: 'barChart'
});
</script>
</body>
@caravinden
Copy link
Author

Object oriented approach to create a simple bar graph

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment