Permalink
Browse files

Refactor Bar Chart

Structure according to [Towards Reusable
Charts](http://bost.ocks.org/mike/chart/)
  • Loading branch information...
jugglinmike committed Mar 2, 2013
1 parent 65c83b9 commit c9b08827b7646c8634acf6b6231ec6edb2ec1200
Showing with 54 additions and 21 deletions.
  1. +2 −1 index.html
  2. +17 −0 scripts/app.js
  3. +35 −20 scripts/bar-chart.js
View
@@ -5,10 +5,11 @@
<title>D3.chart examples</title>
<script src="scripts/lib/d3.v3.js"></script>
<script src="scripts/datasrc.js"></script>
<script src="scripts/bar-chart.js"></script>
<link rel="stylesheet" href="styles/index.css"></link>
</head>
<body>
<script src="scripts/bar-chart.js"></script>
<script src="scripts/app.js"></script>
<script src="scripts/chord-diagram.js"></script>
</body>
</html>
View
@@ -0,0 +1,17 @@
(function(window, undefined) {
"use strict";
var d3 = window.d3;
var DataSrc = window.DataSrc;
var BarChart = window.BarChart;
var dataSrc = new DataSrc();
var myBarChart = BarChart({ data: dataSrc.data });
myBarChart();
setInterval(function() {
dataSrc.fetch();
myBarChart();
}, 1500);
}(this));
View
@@ -1,34 +1,30 @@
(function(window, undefined) {
window.BarChart = function(options) {
"use strict";
var w = 20,
h = 80,
dataSrc = new DataSrc(),
data = dataSrc.data;
options = options || {};
var w, h,
data = options.data || [];
var x = d3.scale.linear()
.domain([0, 1])
.range([0, w]);
.domain([0, data.length]);
var y = d3.scale.linear()
.domain([0, 100])
.rangeRound([0, h]);
.domain([0, 100]);
var svg = d3.select("body").append("svg")
.attr("class", "chart")
.attr("width", w * data.length - 1)
.attr("height", h);
.attr("class", "chart");
function redraw() {
function chart() {
var rect = svg.selectAll("rect")
.data(data, function(d) { return d.time; });
rect.enter().insert("rect", "line")
.attr("x", function(d, i) { return x(i + 1) - .5; })
.attr("y", function(d) { return h - y(d.value) - .5; })
.attr("width", w)
.attr("width", w / data.length)
.attr("height", function(d) { return y(d.value); })
.transition()
.duration(1000)
@@ -44,10 +40,29 @@
.remove();
}
redraw();
setInterval(function() {
dataSrc.fetch();
redraw();
}, 1500);
chart.width = function(newWidth) {
if (!arguments.length) {
return w;
}
w = newWidth;
x.range([0, w]);
svg.attr("width", w);
return this;
};
chart.height = function(newHeight) {
if (!arguments.length) {
return h;
}
h = newHeight;
y.rangeRound([0, h]);
svg.attr("height", h);
return this;
};
chart.width(options.width || 600);
chart.height(options.height || 80);
return chart;
}(this));
};

0 comments on commit c9b0882

Please sign in to comment.