dimple.js - Dimple Stacked Bar Chart - adding label for aggregate total -
i'm trying add label aggregate total stacked bar chart above each bar. used example (http://dimplejs.org/advanced_examples_viewer.html?id=advanced_bar_labels) add totals each section of bar, i'm not sure how add total above. i've been able add total labels above each bar single series (not stacked). can't work stacked bar chart.
my current workaround plotting additional null series line, making line , markers transparent can still see total value in tooltip. however, i'd have totals displayed above each bar.
here's code:
var svg = dimple.newsvg("#chartcontainer", 590, 400); var mychart = new dimple.chart(svg, data); mychart.setbounds(80, 30, 510, 305); var x = mychart.addcategoryaxis("x", "month"); x.addorderrule(date); var y = mychart.addmeasureaxis("y", "calls"); y.showgridlines = true; y.tickformat = ',6g'; y.overridemin = 0; y.overridemax = 800000; var s = mychart.addseries("metric", dimple.plot.bar); s.afterdraw = function (shape, data) { var s = d3.select(shape), rect = { x: parsefloat(s.attr("x")), y: parsefloat(s.attr("y")), width: parsefloat(s.attr("width")), height: parsefloat(s.attr("height")) }; if (rect.height >= 1) { svg.append("text") .attr("x", rect.x + rect.width / 2) .attr("y", rect.y + rect.height / 2 + 3.5) .style("text-anchor", "middle") .style("font-size", "9px") .style("font-family", "sans-serif") .style("opacity", 0.8) .text(d3.format(",.1f")(data.yvalue / 1000) + "k"); } }; mychart.addlegend(60, 10, 510, 20, "right"); mychart.draw();
here jsfiddle: http://jsfiddle.net/timothymartin76/fusaqyhk/16/
i appreciate assistance on this.
thanks!
you can add them after drawing calculating bar totals , deriving y position that:
// iterate every value on x axis x.shapes.selectall("text").each(function (d) { // there dummy empty string value on end want ignore if (d && d.length) { // total y value var total = d3.sum(data, function (t) { return (t.month === d ? t.calls : 0); }); // add text label var label = svg.append("text"); // set x position // x._scale(d) tick position of each element // (mychart._widthpixels() / x._max) / 2 half of space allocated each element label.attr("x", x._scale(d) + (mychart._widthpixels() / x._max) / 2) // vertically center text on point label.attr("dy", "0.35em") // style text - can better done label.attr("class", "my-label-class") label.style("text-anchor", "middle") .style("font-size", "9px") .style("font-family", "sans-serif") .style("opacity", 0.8) // set text in thousands label.text(d3.format(",.1f")(total / 1000) + "k"); // once style , text set can set y position // y._scale(total) gives y position of total (and therefore top of top segment) // label.node().getbbox().height gives height of text leave gap above bar label.attr("y", y._scale(total) - label.node().getbbox().height) } });
here updated fiddle: http://jsfiddle.net/fusaqyhk/17/
Comments
Post a Comment