Match vertex size to label size in igraph

筅森魡賤 提交于 2019-11-30 14:39:12

Here is an example. Among some dirty tricks (i.e. multiplying the vertex size by 200), the key is to use two plot commands, so that we can measure the width (and height) of the labels with strwidth(), after the plot size is set with the first (empty) plot.

library(igraph)
camp <- graph.formula(Harry:Steve:Don:Bert - Harry:Steve:Don:Bert,
                      Pam:Brazey:Carol:Pat - Pam:Brazey:Carol:Pat,
                      Holly   - Carol:Pat:Pam:Jennie:Bill,
                      Bill    - Pauline:Michael:Lee:Holly,
                      Pauline - Bill:Jennie:Ann,
                      Jennie  - Holly:Michael:Lee:Ann:Pauline,
                      Michael - Bill:Jennie:Ann:Lee:John,
                      Ann     - Michael:Jennie:Pauline,
                      Lee     - Michael:Bill:Jennie,
                      Gery    - Pat:Steve:Russ:John,
                      Russ    - Steve:Bert:Gery:John,
                      John    - Gery:Russ:Michael)

V(camp)$label <- V(camp)$name
set.seed(42)   ## to make this reproducable
co <- layout.auto(camp)

plot(0, type="n", ann=FALSE, axes=FALSE, xlim=extendrange(co[,1]), 
     ylim=extendrange(co[,2]))
plot(camp, layout=co, rescale=FALSE, add=TRUE,
     vertex.shape="rectangle",
     vertex.size=(strwidth(V(camp)$label) + strwidth("oo")) * 100,
     vertex.size2=strheight("I") * 2 * 100)

Btw. this does not really work well with SVG graphics, because there is no way to measure the width of the text from R, the SVG device only makes guesses.

I know that this is not a direct answer to your question but I would suggest to use a different tool for visualization. yEd is very good at adjusting the nodes' width to the label's size. You can also manipulate the visualization easily, and export it to SVG for a final polish. It can be obtained for free from www.yworks.com (Disclaimer: I am not working there).

To export the graph in a well-readable format (yEd does not understand igraph's gml-format), use graphml:

write.graph(graph, "test.graphml", format="graphml")

Open it in yEd. Go to edit-> properties mapper and click on "new configuration (Node)" (the green "plus" symbol, upper left). In the middle of the fram, under "data source", search for the name of your labels (should be 'name'). In the middle tab called "map to" choose "label text" and in the right column leave the "conversion" be set to "Automatic".

Now choose Tools -> fit node to label (the default parameters are fine for a first try) and then choose your favourite layout. You can export to various image-formats but to my knowledge all are implemented using a bitmap-intermediate. Thus, I normally export to SVG and do the polishing in inkscape. If anyone knows a more efficient procedure to get good-looking layouts of medium-sized graphs produced in igraph, let me know.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!