11

d3 has a demo of a Force-Directed Graph Layout.

Instead of circles, I want all nodes in the graph to be images.

so, I changed

 .append("svg:circle")
      .attr("class", "node")
      .attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; })
      .attr("r", 5)
      .style("fill", function(d) { return fill(d.group); })
      .call(force.drag);

to

.append("xhtml:img")
   .attr("src", "http://a577.phobos.apple.com/us/r1000/081/Purple/12/61/13/mzi.lgqdzwfu.png")
   .call(force.drag);

But I can not see any images. What am I doing wrong?

VividD
  • 10,456
  • 6
  • 64
  • 111
Tinyfool
  • 1,460
  • 2
  • 18
  • 40

1 Answers1

18
node.append("svg:image")
    .attr("class", "circle")
    .attr("xlink:href", "https://d3nwyuy0nl342s.cloudfront.net/images/icons/public.png")
    .attr("x", "-8px")
    .attr("y", "-8px")
    .attr("width", "16px")
    .attr("height", "16px");

Here is an example of using an image as the node: http://bl.ocks.org/950642

Christopher Manning
  • 4,527
  • 2
  • 27
  • 36
  • 1
    Do you happen to know how to make the rect image as a circle image inside a circle node? Your given example will show a circle and a rect image inside it. Thanks. – derek May 23 '15 at 05:45
  • @derek, how about border-radius: 100%; css style? – andreybavt Jun 28 '15 at 11:16
  • border-radius doesn't work on svg:image but there is hope: http://stackoverflow.com/questions/7430580/setting-rounded-corners-for-svgimage – fredw Apr 14 '16 at 04:48