Question

I'm trying to reproduce the "tree diagram with images as nodes" .

However, instead of having all nodes with images, I'd like to have some nodes with images and others with the regular circles.

Any ideas?

Is it something I need to change in this part of the code:

nodeEnter.append("image")
  .attr("xlink:href", function(d) { return d.icon; })
  .attr("x", "-12px")
  .attr("y", "-12px")
  .attr("width", "24px")
  .attr("height", "24px");    
Was it helpful?

Solution

There are definitely several significantly different ways to achieve what you want. However, I am going to show you just one way which is both simple and in the spirit of d3 library.


For convenience, I prepared jsfiddle version of the example you mentioned:

link to jsfiddle

enter image description here

(since I couldn't figure out paths to icons from example, I used some that I found on the internet, and I used full internet addresses for them)


Now, let's change two of such internet icon paths to empty string (indicating that circles should be displayed instead of icons), like in this code:

  {
    "name": "Son of A",
    "parent": "Level 2: A",
    "value": 5,
    "type": "steelblue",
    "icon": "",
    "level": "orange"
  },

We have to find the way to select only nodes that contain empty string for icons, and to add circles for them. This is done with following code:

  nodeEnter.filter(function(d) {
            return (d.icon == "");
       })
      .append("circle")
      .attr("cx", "0px")
      .attr("cy", "0px")
      .attr("r", "12px");

That's it!

link to jsfiddle

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top