使用NVD3的响应饼图 [英] Responsive pie chart using NVD3
问题描述
我正在使用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.
我制作了小提琴.确实,它是响应式的,但我无法将图表放入容器中.我的js代码:
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
}
];
如何使图表正确地适合百分比大小的div?
How can I make the chart fit correctly in a percentage sized div?
推荐答案
完成. viewBox属性以该顺序列出图形的最小宽度,最小高度,宽度和高度.因此,我将最后两个值更改为使用width和height.并在css中放置一个min-height属性,以使其适应不断变化的窗口大小.
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)
和小提琴.
另一种选择是使用nv的update()方法:
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;
});
这篇关于使用NVD3的响应饼图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!