可视化iGraph和标签对齐

时间:2018-06-29 12:38:15

标签: r label igraph text-alignment vertex

代码

library(igraph)

g <- graph.tree(n = 2 ^ 3 - 1, children = 2)
node_labels <- c("", "Group A", "Group B", "(1)Text", "(2)I am a longer text", "(3)I am a long long long text", "(4)X")
lay = layout.reingold.tilford(g)  

plot(g,
     vertex.size = 4,                  # node size
     vertex.color = '#C4D8E2',          # node color
     vertex.label = node_labels,        # node labels
     vertex.label.dist = 5,             # node label size
     vertex.label.font = 2,             # node label type (bold)
     vertex.label.degree=0.0,
     margin=c(0,0,0,0),
     layout=-lay[, 2:1]
)

给我一​​个带有标签的图。如何对齐标签1 .. 4,使它们左对齐,在圆旁边,而不是居中对齐?从我的角度来看,第3条是正确的。切换到ggraph是一种选择,但是在这里旋转标签无效。

enter image description here

2 个答案:

答案 0 :(得分:0)

如果您可以手动更改每个标签的距离,如下所示-

plot(g,
     vertex.size = 4,                  
     vertex.color = '#C4D8E2',          
     vertex.label = node_labels,        
     vertex.label.dist = c(0,0,0,0,8,12,0), # vector of distance
     vertex.label.font = 2,            
     vertex.label.degree=0.0,
     margin=c(0,0,0,0),
     layout=-lay[, 2:1]
)

或者您可能想要创建一个函数来从每个顶点获取这些长度。这是我留给您即兴创作的。

t1 <- sapply(node_labels, FUN = nchar)
t2 <- (t1 - min(t1))/ (max(t1) - min(t1))
t2 <- t2*12


plot(g,
     vertex.size = 4,                  
     vertex.color = '#C4D8E2',          
     vertex.label = node_labels,        
     vertex.label.dist = t2, # vector of distance
     vertex.label.font = 2,            
     vertex.label.degree=0.0,
     margin=c(0,0,0,0),
     layout=-lay[, 2:1]
)

答案 1 :(得分:0)

下面是带有计算的代码:

library(igraph)

g <- graph.tree(n = 2 ^ 3 - 1, children = 2)
node_labels <- c("", "Group A", "Group B", "(1)Text", "(2)I am a longer text", "(3)I am a long long long text", "(4)X")
lay = layout.reingold.tilford(g)  

t1 <- sapply(as.vector( node_labels), FUN = strwidth,units='in')
t2 <- (t1 - min(t1))/ (max(t1) - min(t1))*3+0.9


plot(g,
     vertex.size = 4,                  # node size
     vertex.color = '#C4D8E2',          # node color
     vertex.label = node_labels,        # node labels
     vertex.label.dist = t2,             # node label size
     vertex.label.font = 2,             # node label type (bold)
     vertex.label.degree=0.0,
     margin=c(0,0,0,0),
     layout=-lay[, 2:1]
)

这是一个更好的选择,但我做不到完美。