how to add legend to a pie chart using D3js? And how to centralise the pie chart?

让人想犯罪 __ 提交于 2019-11-28 11:30:23

Legends are just rectangle and text you append to svg. Check out population pie chart template on vida.io. It has legend built into the chart:

https://vida.io/documents/gSvr8dAH23eirKQDp

To center the chart, change translate parameter in svg. You have it set to r right now. You can do something like, (width / 2 - r) and (height / 2 - r).

var svg = d3.select("#canvas").append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
    .attr("transform", "translate(" + (width / 2 - r) + "," + (height / 2 - r) + ")");

Here is the example I ran off of http://bl.ocks.org/ZJONSSON/3918369 But you will need d3.legend.js which you should be able to find off that link. Add that in and then do three things.

1st. Add a css class for legend

.legend rect {
 fill:white;
 stroke:black;
 opacity:0.8; }

2nd. Add the attr: data-legend to g.append("path")

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

3rd. Some where after this go ahead and drop this guy in there

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

Then you should have a nice simple legend. If you want to center it, play with values in translate when creating legend (50, 30).

This is what you should end up with.

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