Leon Gaban Leon Gaban - 26 days ago 113
Javascript Question

Adding additional graphs to NVD3 multiChart, shortens the chart (due to legend) what is the fix?

My plunker NVD3 chart

I'm using NVD3's multiChart chart. When I add additional area graphs into the chart, it appears that the legend pushes down the chart. The more graphs get added the more the chart appears scrunched.

enter image description here

enter image description here

Note how the Y axis in the 2 screenshot is almost 50% shorter than the original.




I tried removing the legend with CSS, but the chart still shortens:

.legendWrap {
display: none;
}


Even removed the legend with Javascript and still the chart gets scrunched:

removeElementsByClass('nv-legend');

function removeElementsByClass(className){
var elements = document.getElementsByClassName(className);
while(elements.length > 0){
elements[0].parentNode.removeChild(elements[0]);
}
}


enter image description here

Any idea how to solve this problem?

My full drawChart function:

function drawChart(res) {
console.log('res',res);

nv.addGraph(function() {
chart = nv.models.multiChart()
.margin({
top: 20,
right: 40,
bottom: 50,
left: 40
})
.interpolate("linear") // don't smooth out the lines
.color(d3.scale.category10().range());

chart.xAxis.tickFormat(function(d) {
return d3.time.format('%I:%M')(new Date(d));
});
chart.yAxis1.tickFormat(d3.format(',f'));
chart.yAxis2.tickFormat(function(d) {
return '$' + d3.format(',f')(d)
});

d3.select('svg#chart')
.datum(res)
.transition().duration(500).call(chart);

chart.tooltip.hidden(true);

chart.update();

d3.select('.lines2Wrap').node().parentNode.insertBefore(d3.select('.stack1Wrap').node(), d3.select('.lines2Wrap').node());

// Add top padding to xAxis timeline:
d3.selectAll('.nv-x.nv-axis > .nv-wrap.nv-axis > g > g.tick > text').each(function(d,i) {
d3.select(this).attr('dy', '1.5em');
});

d3.selectAll('.nv-x.nv-axis > .nv-wrap.nv-axis > .nv-axisMaxMin > text').each(function(d,i) {
d3.select(this).attr('dy', '1.5em');
});

nv.utils.windowResize(chart.update);

return chart;
});
}

Answer Source

You are correct, the legend is the cause of the problem. Instead of setting display: none in CSS, you can remove the legend entirely like this:

chart = nv.models.multiChart()
  .margin({
    top: 20,
    right: 40,
    bottom: 50,
    left: 40
  })
  .showLegend(false) // don't show the legend
  .interpolate("linear") // don't smooth out the lines
  .color(d3.scale.category10().range());

Full working code here.