Home Ask Login Register

Developers Planet

Your answer is one click away!

David February 2016

Adapting nvd3 linePlusBarChart to a histogram with cumulative percentage line?

I was looking for options to build histograms, and before I tried to do it in barebones d3, I found nvd3's linePlusBarChart desirable, although the given example wasn't designed for histograms with a cumulative percentage line.

With community help, I managed to get such a chart done in d3. I then went to try to adapt it and got this far.

It seems for some reason, I get 2 charts, a mini preview at the bottom with the larger chart at top, and the line has circular points, that are too big on the large chart. How do I get it to be just one chart, no points on line (or at least very small points), and make it match more like the basic d3 version?

Any suggestions?


WittyID February 2016

I'm not sure if using nvd3 (look/feel) is a requirement for you, but it sounds like you're trying to replicate the d3 histogram example "...make it match more like the basic d3 version?".

If you're fine with a pure d3 version take a look at this fiddle which make small changes to this histogram example.

First, we add a cumulative property to the result of the d3 histogram function

    if(i === 0){
    d.cum = d.y
    d.cum = d.y + data[i-1].cum

Next we create a y scale for the cumulative line

var yc = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d.cum; })])
.range([height, 0]);

Then, declare a line function to make use of our new cum property and yc scale

var line = d3.svg.line()
.x(function(d) { return x(d.x); })
.y(function(d) { return yc(d.cum); });

And finally draw the cumulative line

  .attr("class", "line")
  .attr("d", line);

Regarding the nvd3 example you posted, you can set the chart's 'focusEnable' to false to get rid of the bottom chart.

var chart = nv.models.linePlusBarChart()
        .margin({top: m.top, right: m.right, bottom: m.bottom, left: m.left})
        .x(function(d,i) { return i })
        .y(function(d,i) {return d[1] })

The other issues (big dots and shaded region around line) are css related. Adding nvd3's css file should solve them. See this fiddle.

Hope this helps.

Post Status

Asked in February 2016
Viewed 1,143 times
Voted 10
Answered 1 times


Leave an answer

Quote of the day: live life