简体   繁体   English

带有图像作为标签的d3.js雷达图

[英]d3.js Radar chart with images as labels

I created a d3.js radar chart based on http://bl.ocks.org/nbremer/21746a9668ffdf6d8242 but I'm having trouble adding images to the labels. 我基于http://bl.ocks.org/nbremer/21746a9668ffdf6d8242创建了d3.js雷达图,但在将图像添加到标签时遇到了问题。 The problem is that the images are not centered. 问题是图像未居中。 Here is my actual code atm: 这是我的实际代码atm:

http://leanza.nl/chart/ http://leanza.nl/chart/

The images I use are dummy images but I think it makes the problem obvious. 我使用的图像是虚拟图像,但我认为这使问题显而易见。 Can anyone point me in the right direction? 谁能指出我正确的方向? Thanks is advanced! 感谢先进!

You have to add/sub the half size of the image to x and y coordinates. 您必须在x和y坐标上添加/减去图像的一半大小。

axis.append("svg:image")
  .attr("class", "legend")
  .style("font-size", "11px")
  .attr("text-anchor", "middle")    //  
  .attr("xlink:href", "http://dummyimage.com/60x60/000/ffffff.png")
  .attr("x", function (d, i) { return -30+rScale(maxValue * cfg.labelFactor) * Math.cos(angleSlice * i - Math.PI / 2); })
  .attr("y", function (d, i) { return -30+rScale(maxValue * cfg.labelFactor) * Math.sin(angleSlice * i - Math.PI / 2); })
  .attr("width", 60)
  .attr("height", 60);

In Nadieh Bremer's code, this is what she uses for positioning the labels: 在Nadieh Bremer的代码中,这是她用来放置标签的方式:

.attr("x", function (d, i) { 
    return rScale(maxValue * cfg.labelFactor) * Math.cos(angleSlice * i - Math.PI / 2); })
.attr("y", function (d, i) { 
    return rScale(maxValue * cfg.labelFactor) * Math.sin(angleSlice * i - Math.PI / 2); })

When the labels are only texts, we can easily position the texts right in the centre with a simple: 当标签只是文本时,我们可以通过以下简单的方法轻松地将文本定位在中心:

.attr("text-anchor", "middle")

But there is no text-anchor for images. 但是没有用于图像的text-anchor For a image, x and y refer to the top-left corner. 对于图像, xy指的是左上角。 You can see that in your screenshot, all the small squares have the top-left corner right in the centre: 您可以在屏幕快照中看到,所有小方块的中心都在左上角:

在此处输入图片说明

What we need is just to move all the images upward and leftward, until the centers of the images are in the position were their top left corner were. 我们只需要向上和向左移动所有图像,直到图像的中心位于其左上角的位置。 As all the images have a class named legend (and all of them are 60x60 pixels), you just need: 由于所有图像都有一个称为legend的类(并且所有图像均为60x60像素),因此您只需要:

d3.selectAll(".legend").attr("transform", "translate(-30,-30)");

Alternatively, you can set x and y already with the correct value, as in ego2dot0 answer . 或者,您可以已经将xy设置为正确的值,如ego2dot0 answer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM