MATLAB的树状图:按从上到下的节点高度对齐 [英] MATLAB's treeplot: align by node height from top

查看:208
本文介绍了MATLAB的树状图:按从上到下的节点高度对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在MATLAB上使用treeplot函数得到的结果(这是示例图像):

Here's what I get by using the treeplot function on MATLAB (this is the example image):

这就是我想要得到的:

如您所见,我想根据每个节点到根的距离来确定它们的位置.有可能吗?

As you can see, I'd like to have the position of each node according to its distance from the root. Is that possible?

推荐答案

我也在Matlab中寻找根对齐"树状图,但没有找到解决方案.这是我想出的,以防万一仍然有人需要它(我使用的示例与

I was also looking for a "root-aligned" treeplot in Matlab and found no solution. Here is what I came up with, in case someone is still in need of it (I'm using the same example as in the Matlab documentation):

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

首先,我们需要获取原始树图中每个节点的x和y坐标,并找到其中的所有叶子:

At first we need to get the x and y coordinates of every node in the original tree plot and find all leaves in it:

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

接下来,我们重建树图中的每个链,并将其存储在矩阵中(这样,以后我们可以更改节点的y位置):

Next, we reconstruct every chain in the tree plot and store it in a matrix (by doing so, we can later change the y position of the nodes):

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坐标,并取决于树中的层数:

Now we compute the new y-coordinates determined by the row index in the matrix and dependent on the number of layers in the tree:

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

我们现在可以绘制重新定位的节点并添加连接线:

We can now plot the re-positioned nodes and add the connecting lines:

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

如果愿意,还可以将节点标签添加到图中:

If you like, you can also add the node labels to the plot:

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

结果图如下:

这篇关于MATLAB的树状图:按从上到下的节点高度对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆