在R中创建图表

时间:2016-12-08 11:49:00

标签: r

我想知道是否可以从类似的数据集创建图表,如下面的数据表:

col0                       col1                        col2          col3
name                       <NA>                        <NA>          <NA>      
name   cat, centipede, milipede, snail, flay, worm    cat          vertebrates     
name   cat, centipede, milipede, snail, flay, worm    centipede    arthropods    
name   cat, centipede, milipede, snail, flay, worm    milipede     arthropods      
name   cat, centipede, milipede, snail, flay, worm    snail        mollusc      
name   cat, centipede, milipede, snail, flay, worm    fly          insect    
name   cat, centipede, milipede, snail, flay, worm    worm         invertebrates  

并使用R创建图表,该图表或多或少类似于下图:

enter image description here

1 个答案:

答案 0 :(得分:1)

从以下df开始尝试igraph:

library(igraph)   
df
   col0                                   col1          col2          col3
1  name                                   <NA>          <NA>          <NA>
2  name cat,centipede,milipede,snail,flay,worm   vertebrates        animal
3  name cat,centipede,milipede,snail,flay,worm invertebrates        animal
4  name cat,centipede,milipede,snail,flay,worm           cat   vertebrates
5  name cat,centipede,milipede,snail,flay,worm     centipede    arthropods
6  name cat,centipede,milipede,snail,flay,worm      milipede    arthropods
7  name cat,centipede,milipede,snail,flay,worm    arthropods invertebrates
8  name cat,centipede,milipede,snail,flay,worm       mollusc invertebrates
9  name cat,centipede,milipede,snail,flay,worm         snail       mollusc
10 name cat,centipede,milipede,snail,flay,worm        insect invertebrates
11 name cat,centipede,milipede,snail,flay,worm           fly        insect
12 name cat,centipede,milipede,snail,flay,worm          worm invertebrates

df <- df[df$col1 != '<NA>',]
species <- union(df$col3, df$col2)
df <- df[c('col3', 'col2')]
names(df) <- c('from', 'to')
g <- graph.data.frame(df, directed = TRUE, vertices = species)
plot(g,vertex.size=2, vertex.label.dist=0.5, vertex.color="cyan", 
     edge.arrow.size=0.5, layout=layout.reingold.tilford(g, root='animal'))

enter image description here