Message Boards Message Boards

[?] Create Multi-coloured tree plot?

Posted 7 years ago

I am trying to create a multi-coloured tree plot (Mathematica 9) where each branch is coloured according to its parent node value. For example, for a tree plot with three nodes, n1, n2 and n3, coming from a single parent node (n0), the children nodes of n1 should be red & n2 green and n3 should be blue.

TreePlot[nodes, EdgeRenderingFunction -> ({Red, Line[#1]} &), VertexRenderingFunction -> (Inset[Row[{If[Last[#2] > 3, Rotate[Last[#2], 90 Degree], Last[#2]]}], #1, Background -> White] &)]

I am using the EdgeRenderingFunction for this within the following expression which will render the edges of the tree plot. The problem, I think, is that the If statement is not evaluated straight away and so the compiler does not recognise the first option (contained within the If statement) as a relevant one. As you can see I'm trying to create a tree plot with red and green branches.

TreePlot[nodes, EdgeRenderingFunction -> ({If[Last[#2] === 1, Red, Green], Line[#1]} &), VertexRenderingFunction -> (Inset[Row[{If[Last[#2] > 3, Rotate[Last[#2], 90 Degree], Last[#2]]}], #1, Background -> White] &)]

Here, all edges were rendered the same colour. Not sure whether EdgeRenderingFunction[] renders the whole tree object instead of it's parts or whether I need to include the edge colour into the tree data structure (node table)?

Here's a sample of the node list: {{0} -> {0, 1}, {0} -> {0, 2}, {0} -> {0, 3}, {0, 1} -> {0, 1, 4}, {0, 1} -> {0, 1, 5}, {0, 1} -> {0, 1, 6}, {0, 1} -> {0, 1, 7}, {0, 1} -> {0, 1, 8}...

Thanks for your time in helping me with this.

POSTED BY: Marc Edwards

Marc,

The If comparison needs to be a node, not a number:

nodes = {{0} -> {0, 1}, {0} -> {0, 2}, {0} -> {0, 3}, {0, 1} -> {0, 1,
     4}, {0, 1} -> {0, 1, 5}, {0, 1} -> {0, 1, 6}, {0, 1} -> {0, 1, 
    7}, {0, 1} -> {0, 1, 8}, {0, 1} -> {0, 1}}
TreePlot[nodes, 
 EdgeRenderingFunction -> ({If[First[#2] == {0, 1}, Red, Green], 
     Arrow[#1]} &), 
 VertexRenderingFunction -> (Inset[
     Row[{If[Last[#2] > 3, Rotate[Last[#2], 90 Degree], 
        Last[#2]]}], #1, Background -> White] &)]

to get

enter image description here

or a single node:

TreePlot[nodes,EdgeRenderingFunction->({If[First[#2]=={0},Red,Green],Arrow[#1]}&),VertexRenderingFunction->(Inset[Row[{If[Last[#2]>3,Rotate[Last[#2],90 Degree],Last[#2]]}],#1,Background->White]&)]

to get

enter image description here

I am not sure why testing if Last[#2] equals a number throws an error since Mathematica knows that a list can't equal a number but either way, you need a list in that position, not a number. I guess by throwing an error it lets you know that it can never do that test properly.

POSTED BY: Neil Singer
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract