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?
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With