Responsive Pie Chart Using NVD3

I am working on a simple example pie chart using NVD3. It displays correctly, but it does not respond. I tried to fulfill this answer to make it responsive, but did not quite understand.

I made a fiddle . Indeed, this is responsive, but I cannot put the chart in a container. My js code is:

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 to set up a chart in a div as a percentage?

+5
source share
1 answer

Done. The viewBox attribute lists the minimum width, minimum height, width, and height of the graph in that order. So, I changed the last two values ​​to use width and height instead. And set the min-height property to css only so that it adapts to resize the window.

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

And fiddle .

Another option is to use the nv 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; }); 
+2
source

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


All Articles