是否可以用D3在圆环图的弧中插入一个图标

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

本文关键字:插入 图标 一个 D3 圆环图 是否      更新时间:2023-09-26

我有一个甜甜圈图,有三个类别(弧形):Facebook(50%)、Twitter(30%)和Instagram(20%)。绘制图表相当容易,但我想知道如何在每个弧中插入一个带有社交网络相应符号的图标(使用D3甚至C3)。

谢谢!

添加图像只是使用的一种情况

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

您还需要定位(xy)。这些将默认为0,因此您也可以使用translate,类似这样的东西来找到弧的中心:

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

然而,这只是将图像的右上角固定在弧的中心,因此要使其正确居中,需要使用图像的大小。以下是全部内容:

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

以下是一个示例:http://jsfiddle.net/henbox/88t18rqg/6/

请注意,我已经在图表数据中包含了图像路径。你只需要去寻找合适的图标!