D3 and Javascript: Uncaught TypeError: Cannot read property 'apply' of undefined

D3 and Javascript: Uncaught TypeError: Cannot read property 'apply' of undefined

我是 D3 的新手,JavaScript,我正在尝试建立一个基本的圆环图,但由于这个错误而陷入困境。我可以看到值进入 donutChartData,但图表仍然无法在浏览器上显示。 .call(donutChart);

行发生错误

异常:

Uncaught TypeError: Cannot read property 'apply' of undefined
    at Array.Co.call (d3.min.js:3)
    at Socket.<anonymous> (main.js:137)
    at Socket.Emitter.emit (socket.io.js:7414)
    at Socket.onevent (socket.io.js:7130)
    at Socket.onpacket (socket.io.js:7088)
    at Manager.<anonymous> (socket.io.js:7520)
    at Manager.Emitter.emit (socket.io.js:7414)
    at Manager.ondecoded (socket.io.js:2823)
    at Decoder.<anonymous> (socket.io.js:7520)
    at Decoder.Emitter.emit (socket.io.js:2285)

代码:

var donutChart;
var donutChartData;

//Donut chart example
nv.addGraph(function() {
 donutChart = nv.models.pieChart()
      .x(function(d) { return d.label })
      .y(function(d) { return +d.value })
      .showLabels(true)     //Display pie labels
      .labelThreshold(.05)  //Configure the minimum slice size for labels to show up
      .labelType("percent") //Configure what type of data to show in the label. Can be "key", "value" or "percent"
      .donut(true)          //Turn on Donut mode. Makes pie chart look tasty!
      .donutRatio(0.35);  //Configure how big you want the donut hole size to be.     

   d3.select("#Chart4 svg")
        .datum(donutChartData)
        //.transition().duration(350)
        .call(donutChart); /// ERROR OCCURRED ON THIS LINE

  return donutChart;
});


socket.on("donutChartData",function(dChartData){
    donutChartData=dChartData; 
    console.log("Donut Chart: ",dChartData[0].label,dChartData[0].value);
       d3.select("#Chart4 svg")
        .datum(dChartData)
        ///.transition().duration(350)
        .call(donutChart);
     //donutChart.update();
});

你的代码应该是这样的:

var donutChart;
var donutChartData;
function drawChart() {
//Donut chart example
nv.addGraph(function() {
donutChart = nv.models.pieChart()
  .x(function(d) { return d.label })
  .y(function(d) { return +d.value })
  .showLabels(true)     //Display pie labels
  .labelThreshold(.05)  //Configure the minimum slice size for labels to show up
  .labelType("percent") //Configure what type of data to show in the label. Can be "key", "value" or "percent"
  .donut(true)          //Turn on Donut mode. Makes pie chart look tasty!
  .donutRatio(0.35);  //Configure how big you want the donut hole size to be.     

  d3.select("#Chart4 svg")
    .datum(donutChartData)
    //.transition().duration(350)
    .call(donutChart); /// ERROR OCCURRED ON THIS LINE

 return donutChart;
});
}


socket.on("donutChartData",function(dChartData){
    donutChartData=dChartData; 
    console.log("Donut Chart: ",dChartData[0].label,dChartData[0].value);
    drawChart();
});

您必须在获得图表数据后绘制图表,您现在没有在做。