Skip to content

Instantly share code, notes, and snippets.

@NelsonMinar
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NelsonMinar/11524926 to your computer and use it in GitHub Desktop.
Save NelsonMinar/11524926 to your computer and use it in GitHub Desktop.
Simple D3 modular chart

A very, very simple modular chart based on [Mike Bostock's recommendation](// A very, very simple D3 modular chart based on http://bost.ocks.org/mike/chart/)

Creates a new chart type "histobar" that when insantiated, renders the data as a string in an SVG. Obviously not useful in itself, but the simplest possible reusable chart as a place to start.

// A very, very simple D3 modular chart based on http://bost.ocks.org/mike/chart/
function histobar() {
var width = 720, // default width
height = 80; // default height
function my(selection) {
selection.each(function(d, i) {
// Select the svg element, if it exists
var svg = d3.select(this).selectAll("svg").data([data]);
// Create a g inside the svg
var g = svg.enter().append("svg").append("g");
// Set the svg node parameters
svg.attr("width", width);
svg.attr("height", height);
// Render the chart
g.append("text").text(d).attr("transform", "translate (0,10)");
});
}
my.width = function(value) {
if (!arguments.length) return width;
width = value;
return my;
};
my.height = function(value) {
if (!arguments.length) return height;
height = value;
return my;
};
return my;
}
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
background-color: #eef;
}
svg { background-color: #fee; }
text { font: 10px sans-serif; }
</style>
<body>
<h1>Histogam bar demo</h1>
<div id="chartArea"></div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="histobar.js"></script>
<script>
var data = [1, 1, 2, 3, 5, 8];
var chart = histobar();
d3.selectAll("#chartArea").data([data]).call(chart);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment