"TypeError: r is null" when creating d3 pie chart

"TypeError: r is null" when creating d3 pie chart

我正在使用 d3 v4。我正在尝试使用以下代码创建一个简单的饼图

var svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height"),
    radius = Math.min(width, height) / 2,
    g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var color = d3.scaleOrdinal(["#98abc5", 
                 "#8a89a6", 
                 "#7b6888", 
                 "#6b486b", 
                 "#a05d56", 
                 "#d0743c", 
                 "#ff8c00",
                 "#e34d01",
                 "#ccff05",
                 "#3e7eca",
                 "#aa0092",
                 "#b32e4f"]);

var pie = d3.pie()
    .sort(null)
    .value(function(d) { return d.market_cap; });

var path = d3.arc()
    .outerRadius(radius - 10)
    .innerRadius(0);

var label = d3.arc()
    .outerRadius(radius - 40)
    .innerRadius(radius - 40);

var csvData = "currency,market_cap";
csvData += "Ethereum,36536577384"; 
csvData += "Ripple,9562570727"; 
csvData += "Bitcoin Cash,10407237657"; 
csvData += "Litecoin,4537371026"; 
csvData += "NEM,2962953000"; 
csvData += "Dash,2903791940"; 
csvData += "IOTA,2289563023"; 
csvData += "Ethereum Classic,1955610226"; 
csvData += "NEO,1599450000"; 
csvData += "Monero,2170429814"; 
csvData += "Stratis,703350671"; 
csvData += "Bitcoin,80149315484"; 
var data = d3.csvParse(csvData);
data.forEach(function(d) {
  d.market_cap = +d.market_cap;
  return d;
});


  var arc = g.selectAll(".arc")
    .data(pie(data))
    .enter().append("g")
      .attr("class", "arc");

  arc.append("path")
      .attr("d", path)
      .attr("fill", function(d) { return color(d.data.currency); });

  arc.append("text")
      .attr("transform", function(d) { return "translate(" + label.centroid(d) + ")"; })
      .attr("dy", "0.35em")
      .text(function(d) { return d.data.currency; });

我在这里创建了一个演示 -- https://jsfiddle.net/rgw12x8d/12/。但是,根据 运行 代码,它会导致一个神秘的

TypeError: r is null

这是什么意思,但更重要的是,我该如何解决?

在你的 JSFiddle 中,d3.select 没有选择任何东西,因为你有 load type: no wrap - in head,而它应该是 load type: no wrap - in body

除此之外,您 "faking" CSV 的方式是错误的。您正在连接字符串,但没有向它们添加换行符。一个更简单的替代方法是使用 template literals:

var csvData = `currency,market_cap
Ethereum,36536577384
Ripple,9562570727
Bitcoin Cash,10407237657
Litecoin,4537371026
NEM,2962953000
Dash,2903791940
IOTA,2289563023
Ethereum Classic,1955610226
NEO,1599450000
Monero,2170429814
Stratis,703350671
Bitcoin,80149315484`;

这是更新后的 fiddle:https://jsfiddle.net/n3xrbnzj/