Stacked Bar Chart
Want values as labels at the top of each region
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/d3/3.2.2/d3.v3.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/nvd3/1.0.0-beta/nv.d3.js"></script>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/nvd3/1.0.0-beta/nv.d3.css">
<div id="chart">
<svg></svg>
</div>
CSS
#chart svg {
height: 400px;
}
JavaScript
var chart = nv.models.multiBarHorizontalChart().margin({
top: 30, right: 20, bottom: 50, left: 100
});
chart.multibar.stacked(true);
chart.showControls(false);
d3.select('#chart svg').datum([{
key: "S1",
color: "#51A351",
values: [{
x: "This is a really looong label",
y: 40
}, {
x: "Short label",
y: 30
}]
}]).transition().duration(500).call(chart);
d3.selectAll(".nv-x.nv-axis .tick text").each(function(i, e) {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word, line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
// TDOD : Make 80 a dynamic value based on the bar width/height
if (tspan.node().getComputedTextLength() > 80) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});