Change value in legend in dc.js

I built a pie chart with dc.js with the following:

var chart = dc.pieChart(selector, this.chartGroup)
  .width(200).height(200)
  .dimension(this.dimension)
  .group(this.group)
  ...
  .legend(dc.legend().x(10).y(255).gap(5).horizontal(true))

chart.render()

Is there a way to format labels above a legend using the following:

function (d) {
  return d.key + ': ' + d.value;
}
+4
source share
3 answers

I also needed to add (%) to the pieChart legend for several charts. I finished modifying a copy of legend.js from dc.js-2.0.0-beta.5 \ src and included this in my pages.

See http://jsfiddle.net/za8ksj45/36/ for a working example.

    The first ~260 lines is the modified legend.js that can be put in a separate file.
    (I don't have a place I could serve it from so I had to include the file content).

    The main modification starts at line ~88

            itemEnter.append('text')
            .text(function(d) { 
                var legendText = d.name;
                if (_showPercent) {
                    var groupTotal = d.chart.group().all().reduce(function(a, v){ return a + v.value; }, 0);
                    //legendText = legendText + " (" + (100*d.data/groupTotal).toFixed(_percentDecimals) + "%)";
                    //legendText = legendText + " = " + (100*d.data/groupTotal).toFixed(_percentDecimals) + "%";
                    legendText = legendText + " - " + (100*d.data/groupTotal).toFixed(_percentDecimals) + "%";                                              
                }
                return legendText; 
            })
            .attr('x', _itemHeight + LABEL_GAP)
            .attr('y', function () {
                return _itemHeight / 2 + (this.clientHeight ? this.clientHeight : 13) / 2 - 2;
            });

The modification consists of two new methods for the legend ()
 .displayPercent (default = false, to keep the original behavior the same)
 .percentDecimals (default = 1)

:

 var groupTotal = d.chart.group().all().reduce(function(a, v){ return a + v.value; }, 0);

, pieChart, .

, . , : - (%%), %% . , , .

, . stackoverflow, . , .

+3

. :

    .legend(dc.legend().x(100).y(400).itemHeight(13).gap(5).autoItemWidth(true).legendText(function (d) {
        return d.name + " " + Math.round((d.data / totalPrice) * 100) + "%"
    }));

d.name - , . d.data - .

+3

Now you can just use the method .legendText()in the object dc.legend()!

In your particular case, the solution would be:

var chart = dc.pieChart(selector, this.chartGroup)
  .width(200).height(200)
  .dimension(this.dimension)
  .group(this.group)
  ...
  .legend(dc.legend().x(10).y(255).gap(5).horizontal(true).legendText(function(d) {
    return d.key + ': ' + d.value;
  }))

chart.render();

This method is defined here .

+1
source

Source: https://habr.com/ru/post/1529075/


All Articles