在图上添加图例-D3 [英] Adding legend to plot - d3

查看:95
本文介绍了在图上添加图例-D3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

绘制甜甜圈图后,我尝试根据以下示例添加图例:

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

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

但是,我收到此错误:

TypeError:未定义不是对象(正在评估"n.apply")

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

我已经打印了第131行的返回,并且所有的图例名称都被打印了.我不知道是什么导致 undefined error 打印.

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.

这是我的主要代码:

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)

这是一个最小的示例:

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

推荐答案

您需要上传代码 http://bl.ocks.org/ZJONSSON/3918369#d3.legend.js 来查找Javascript中的图例(只需将其复制并粘贴代码即可,它就是函数 d3.legend ).

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).

这篇关于在图上添加图例-D3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆