Stacked-Bar chart with Category Total Labels at the top of the plot panel

by duarteleao

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.19/require.min.js"></script>
<script src="//webdetails.github.io/ccc/charts/lib/amd/require.config.js"></script>
<script src="//webdetails.github.io/ccc/charts/lib/q01-01.js"></script>
<div id="cccExample"></div>

JavaScript

require([
  "ccc/pvc", 
  "ccc/def", 
  "ccc/protovis"
], function(pvc, def, pv) {

    // debug layout
    // def.setDebug(16);

    new pvc.BarChart({
        canvas: "cccExample",
        width:   450,
        height:  400,
        title:   "Stacked-Bar Chart with Category Total Labels at the top of the plot panel",
        animate:    false,
        selectable: true,
        hoverable:  true,
        stacked:    true,
        valuesVisible: true,

        // Adjusts top (and bottom :-/ ) plot paddings to 5% of domain
        // to reserve some space to the total labels.
        orthoAxisOffset: 0.05,

      plot_add: function() {
        return new pv.Label()
          .data(function() {
            // A Bar chart's visibleData is grouped 
            // by Category > Series.
            var cccContext = this.getContext();
            // Return the category Data children.
            return cccContext.panel.visibleData().childNodes;
          })
          .font('bold 12px sans-serif')
          .top(0)
          .textBaseline('top')
          .textAlign('center')
          .left(function(catData) {
          // Scales use the keys, not the values.
          return this.getContext()
              .panel.axes.base.scale(catData.key);
          })
          .text(function(catData) {
            // Getting the sum of each category is easy.

            // The name of the dimension to which the 
            // "value" visual role is bound.
            var valueDimName = this.getContext()
            .panel.visualRoles.value.firstDimensionName();

            // catData's local dimension object
            var valueDim = catData.dimensions(valueDimName);

            // Sum the value dimension over all 
            // Datums in catData.
            var catSum = valueDim.sum();

            // Now format it with the value 
            // dimension's formatter.
            return valueDim.format(catSum);
          });
      }
    })
    .setData(relational_01_neg /*...