Adding legend to plot - d3

拥有回忆 提交于 2021-01-28 22:58:26

问题


After plotting a donut chart, I'm trying to add some legend, based on the following example:

http://bl.ocks.org/ZJONSSON/3918369

However, I'm receiving this error:

TypeError: undefined is not an object (evaluating 'n.apply')

I've printed the return of line 131 and all the legend names are printed. I don't know what's is causing the undefined error print.

This is my main code:

var width = 300,
  height = 300,
  radius = Math.min(width, height) / 2;

var color = d3.scale.ordinal()
  .range(colorrange);

var arc = d3.svg.arc()
  .outerRadius(radius - 10)
  .innerRadius(radius - 70);

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

var svg = d3.select("#info").attr("align", "center").append("svg")
  .attr("class", "piechart")
  .attr("width", width)
  .attr("height", height)
  .append("g")
  .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

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

g.append("path")
  .attr("d", arc)
  .attr("data-legend", function(d) {
    return d.data.name;
  })
  .style("fill", function(d, i) {
    return color(i);
  });

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

legend = svg.append("g")
  .attr("class", "legend")
  .attr("transform", "translate(50,30)")
  .style("font-size", "12px")
  .call(d3.legend)

And this is a minimal example:

https://jsfiddle.net/g6vyk7t1/12/


回答1:


You need to upload the code http://bl.ocks.org/ZJONSSON/3918369#d3.legend.js for the legend in your Javascript (just copy-and-paste it the code, it's the function d3.legend).



来源:https://stackoverflow.com/questions/34730667/adding-legend-to-plot-d3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!