2016-10-04 109 views
1

这里节点高度一致就是我获得通过使用MATLAB的treeplot功能(这是示例图像):MATLAB的treeplot:从顶部

enter image description here

这是我想获得什么:

enter image description here

正如你可以看到,我想有根据从根的距离的每个节点的位置。那可能吗?

+0

你究竟想要什么?没有标签的情节?或者每个节点的'[x,y]'位置? – hbaderts

+0

我想要所有与根等距的节点位于同一水平线上。正如我写的,标签不相关。 – Paul

回答

1

我还在Matlab中寻找“根对齐”的树形图,发现没有解决方案。以下是我想出了,万一有人仍然需要它(我使用的是相同的例子如Matlab documentation):

nodes = [0 1 2 2 4 4 4 1 8 8 10 10]; 

首先,我们需要得到x和y坐标在原树情节的每一个节点,并找到所有的树叶在它:

[x,y] = treelayout(nodes); 
leaves = find(y == min(y)); 

接下来,我们重构每个链树情节和它(存储在一个矩阵通过这样做,我们以后可以改变的y位置节点):

num_layers = 1/min(y)-1; 
chains = zeros(num_layers, length(leaves)); 
for l=1:length(leaves) 
    index = leaves(l); 
    chain = []; 
    chain(1) = index; 
    parent_index = nodes(index); 
    j = 2; 
    while (parent_index ~= 0) 
     chain(j) = parent_index; 
     parent_index = nodes(parent_index); 
     j = j+1; 
    end 
    chains(:,l) = padarray(flip(chain), [0, num_layers-length(chain)], 'post'); 
end 

现在我们计算由矩阵的行索引和依赖层的树的数量确定的新y坐标:

y_new = zeros(size(y)); 
for i=1:length(nodes) 
    [r,c] = find(chains==i, 1); 
    y_new(i) = max(y) - (r-1)*1/(num_layers+1); 
end 

现在,我们可以画出重新定位节点,并添加连接线:

plot(x, y_new, 'o'); 
hold on 
for c=1:size(chains, 2) 
    line_x = x(chains(chains(:,c)>0, c)); 
    line_y = y_new(chains(chains(:,c)>0, c)); 
    line(line_x, line_y); 
end 

如果你愿意,你也可以在节点标签添加到情节:

for t=1:length(nodes) 
    text(x(t)+0.025, y_new(t), num2str(t)); 
end 
xlim([0 1]); 
ylim([0 1]); 

由此得出的数字如下所示: root-aligned treeplot