如何设置nvd3图表的高度和宽度

los*_*rje 22 nvd3.js

我正在尝试使用编程方式设置nvd3多条形图的宽度和高度

chart.width(600);
chart.height(400);
Run Code Online (Sandbox Code Playgroud)

看这里的例子:

http://jsfiddle.net/hPgyq/20/

正如你所看到的,这真的搞砸了图表.我知道我可以做到这一点是CSS:

#chart svg {
  width: 600px;
  height: 400px;
}
Run Code Online (Sandbox Code Playgroud)

但我认为这也可以使用图表上的width()和height()函数.我在这里做错了什么,或者我错误地使用了这两个功能?

sha*_*r90 34

是的,有可能,就像您指定了图表的宽度和高度一样,您必须使用d3.select并设置其宽度和高度属性.

修改代码是下方有代码的版本在这里

function visualizeData(data) {
    nv.addGraph(function() {
        var width = 600, height = 400;
        chart = nv.models.multiBarChart().x(function(d) {
            return d.x;
        }).y(function(d) {
            return d.y;
        }).color(['#aec7e8', '#7b94b5', '#486192']).stacked(true)
        //.margin({top:150,right:150,bottom:150,left:150})
        .width(width).height(height);

        chart.multibar.hideable(false);

        chart.xAxis.showMaxMin(true).tickFormat(d3.format(',f'));

        chart.yAxis.tickFormat(d3.format(',.1f'));

        d3.select('#chart svg').datum(data).transition().duration(500).call(chart).style({ 'width': width, 'height': height });

        nv.utils.windowResize(chart.update);

        return chart;
    });
}
Run Code Online (Sandbox Code Playgroud)

  • 我相信对`width`和`height`的调用是设置图表的宽度和高度属性,而使用width和height属性调用`attr`是设置绘制图表的svg的宽度和高度到. (4认同)