Is it possible to insert an icon in the arc of a donut chart with D3?

烈酒焚心 提交于 2019-12-05 05:35:40

问题


I have a Donut Chart with 3 categories (arcs): Facebook (50%), Twitter(30%) and Instagram(20%). Plot the chart is fairly easy, but I want to know how to insert an icon in each arc with the respective symbol of the social network (using D3 or even C3).

Thanks!


回答1:


Adding an image is just a case of using

...
.append("svg:image")
.attr("xlink:href","myimage.png")
.attr("width", "32")
.attr("height", "32");

You'll also need to position (x and y). These will default to 0, so you could alternatively make use of a translate, something like this to find the center of the arc:

.attr("transform", function(d){
    return "translate(" + arc.centroid(d) + ")";
});

However, that just anchors the image's top-right corner to the centre of the arc, so to properly centre it you need to use the size of the image. Here's the full thing:

var image_width = 32;
var image_height = 32;

// add the image
arcs.append("svg:image").attr("transform", function(d){
    // Reposition so that the centre of the image (not the top left corner)
    // is in the centre of the arc
    var x = arc.centroid(d)[0] - image_width/2;
    var y = arc.centroid(d)[1] - image_height/2;
    return "translate(" + x + "," + y + ")";
})
.attr("xlink:href",function(d) { return d.data.icon;})
.attr("width", image_width)
.attr("height", image_height);

Here's an example: http://jsfiddle.net/henbox/88t18rqg/6/

Note that I've included the image paths in the chart data. You just need to go and find proper icons!



来源:https://stackoverflow.com/questions/26690852/is-it-possible-to-insert-an-icon-in-the-arc-of-a-donut-chart-with-d3

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