简体   繁体   中英

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. The problem is that the images are not centered. Here is my actual code atm:

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.

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:

.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. For a image, x and y refer to the top-left corner. 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:

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

Alternatively, you can set x and y already with the correct value, as in ego2dot0 answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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