簡體   English   中英

使用NVD3的響應餅圖

[英]Responsive pie chart using NVD3

我正在研究一個使用NVD3的餅圖的簡單示例。 它呈現正確,但沒有響應。 我試着按照這個答案讓它響應,但沒有完全達到它。

我做了一個小提琴 實際上,它是響應性的,但我無法將圖表放入容器中。 我的js代碼:

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中正確匹配?

完成。 viewBox屬性按順序列出圖形的最小寬度,最小高度,寬度和高度。 因此,我將最后兩個值更改為使用寬度和高度。 並在css中放置一個min-height屬性,以使其適應不斷變化的窗口大小。

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

小提琴

另一種選擇是使用nv的update()方法:

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;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM