Basic Label Example
by Nivaldo
HTML
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://omnipotent.net/jquery.sparkline/2.1.2/jquery.sparkline.js"></script>
<h1>Over Here, Captain</h1>
<p>Casualties by division in <cite>Star Trek</cite>'s original series.</p>
<svg>
<rect id="backdrop" />
<g id="chart">
<g id="art" />
<g id="labels" />
</g>
</svg>
<p>Data from <a href="http://en.memory-alpha.org/wiki/Portal:Main">Memory Alpha</a>, compiled by <a href="http://preview.tinyurl.com/af7ur8q">Matthew Barsalou</a>.
CSS
/* Styles for our labels */
.htmlLabel {
font-family: arial,helvetica,'sans-serif';
font-size: 12px;
padding: 8px;
background-color: rgba(255,255,255,.3)
}
.htmlLabel p {
margin: 0;
}
.bar-label {
font-size: 18px;
text-align: center;
}
p.description {
margin-top: 8px;
}
/* IE specific label */
.label {
font-family: arial,helvetica,'sans-serif';
font-size: 24px;
text-anchor: middle;
alignment-baseline: text-before-edge;
}
/* Assign styles to bars based on division labels */
.com {
fill: goldenrod;
}
.sci {
fill: royalblue;
}
.ops {
fill: crimson;
}
svg {
border: 1px #000 solid;
}
#backdrop {
fill: oldlace;
}
JavaScript
// Our dataset, based on data from
// http://en.memory-alpha.org/wiki/Portal:Main and
// collected by Matthew Barsalou, http://preview.tinyurl.com/af7ur8q
over_here_captain = [
{
division: "com",
display_division: "Command",
display_color: "Gold",
casualties: 9
},
{
division: "sci",
display_division: "Sciences",
display_color: "Blue",
casualties: 7
},
{
division: "ops",
display_division: "Operations",
display_color: "Red",
casualties: 24
}
];
// Define the size of our chart and
// some common layout properties
cDim = {
height: 500,
width: 500,
barMargin: 10
};
/*
* Chart drawing block
* We have to have something to label before
* we can label anything.
*/
// Let's precalculate the bar width. We can
// get away with this because the data set
// is not dynamic.
// Figure out how much space is actually available
// for the bars.
marginlessWidth = cDim.width - (cDim.barMargin * (over_here_captain.length - 1));
cDim.barWidth = marginlessWidth / over_here_captain.length;
// Set the height and width of our SVG element
svg = d3.select("svg").attr({
height: cDim.height,
width: cDim.width
});
// Set the height and width of our backdrop rect
backdrop = d3.select("#backdrop").attr({
x:0,
y:0,
height: cDim.height,
width: cDim.width
});
// Store references to our two layers.
// "Art" is our chart canvas and "labels,"
// funnily enough, is where we're going to
// put our labels.
art = d3.select("#art");
labels = d3.select("#labels");
// Let's make a scale so the bar data fills the chart space.
// First, we need to get the maximum value of our data set
maxHeight = d3.max(over_here_captain,function(d,i){ return d.casualties });
// Now make the scale function.
barHeight = d3.scale.linear()
.domain([0,maxHeight])
.range([0,cDim.height]);
// Join our data to the...