Search code examples
javascriptd3.jschartsdonut-chartc3.js

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


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!


Solution

  • 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!