Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Responsive pie chart using NVD3

I'm working on a simple example of a pie chart using NVD3. It renders correctly but it is not responsive. I tried to follow this answer to make it responsive, but didn't quite get to it.

I made a fiddle. Indeed, it is responsive, but I'm not able to fit the chart in the container. My js code:

nv.addGraph(function() {
  var chart = nv.models.pieChart()
  .x(function(d) { return d.label })
  .y(function(d) { return d.value })
  .showLabels(true);

  var $container = $('#chart'),
      width = $container.width(),
      height = $container.height();

  d3.select("#chart svg")
    .attr("width", '100%')
    .attr("height", '100%')
    .attr('viewBox','0 0 '+Math.min(width,height)+' '+Math.min(width,height))
    .attr('preserveAspectRatio','xMinYMin')
    .attr("transform", "translate(" + Math.min(width,height) / 2 + "," + Math.min(width,height) / 2 + ")")
    .datum(exampleData)
    .transition().duration(350)
    .call(chart);

  return chart;
});

var exampleData = [
  { 
    "label": "One",
    "value" : 29.765957771107
  } , 
  { 
    "label": "Two",
    "value" : 0
  } , 
  { 
    "label": "Three",
    "value" : 32.807804682612
  } , 
  { 
    "label": "Four",
    "value" : 196.45946739256
  } , 
  { 
    "label": "Five",
    "value" : 0.19434030906893
  } , 
  { 
    "label": "Six",
    "value" : 98.079782601442
  } , 
  { 
    "label": "Seven",
    "value" : 13.925743130903
  } , 
  { 
    "label": "Eight",
    "value" : 5.1387322875705
  }
];

How can I make the chart fit correctly in a percentage sized div?

like image 825
dalvallana Avatar asked Oct 31 '22 08:10

dalvallana


1 Answers

Done. The viewBox attribute lists the min width, min height, width and height of the graph, in that order. So, I changed the last two values to use width and height instead. And put a min-height property in the css just to make it adapt to changing window size.

.attr('viewBox','0 0 '+width+' '+height)

And the fiddle.

Another option is to use the nv's update() method:

nv.addGraph(function() {
  var chart = nv.models.pieChart()
  .x(function(d) { return d.label })
  .y(function(d) { return d.value })
  .showLabels(true);

  var $container = $('#chart'),
      width = $container.width(),
      height = $container.height();

  d3.select("#chart svg")
    .datum(exampleData)
    .transition().duration(350)
    .call(chart);

    nv.utils.windowResize(chart.update);

  return chart;
});
like image 88
dalvallana Avatar answered Nov 09 '22 15:11

dalvallana