Cheng
Cheng

Reputation: 193

How to plot a directed graph with the designated start point in R

Here is the data I use to test,which is in graph.txt:

1 2
1 3
2 5
3 4
3 5
4 5
5 6
5 10
6 7
7 8
7 9
7 12
8 9
9 10
9 4
9 12
10 11
11 2
11 12

I use the graph.data.frame to plot the directed graph. the code is:

 xlist<-read.table("graph.txt")
 xlist <- graph.data.frame(xlist)
 plot(xlist)

It can only plot the graph as followed enter image description here But I only want to plot the start point is 5 ,that is 5->6->... and '5->10->..., how can I do to achieve this

Upvotes: 0

Views: 419

Answers (2)

lukeA
lukeA

Reputation: 54237

There are many ways to exclude 1 to 4. Here's another one:

xlist<-read.table(text = "1 2
1 3
2 5
3 4
3 5
4 5
5 6
5 10
6 7
7 8
7 9
7 12
8 9
9 10
9 11
9 12
10 11
11 7
11 12")
library(igraph)
g <- graph.data.frame(xlist)
set.seed(1)
coords <- layout.fruchterman.reingold(g)
par(mfrow = c(1, 2))
plot(g, layout = coords)
plot(induced.subgraph(g, setdiff(V(g), 1:4)), 
     layout = coords[-(1:4), ])

enter image description here

Upvotes: 1

Stibu
Stibu

Reputation: 15897

With the igraph package, the following worked:

xlist<-read.table("graph.txt")
xlist.sub <- subset(xlist,V1>=5)
xlist.sub <- graph.data.frame(xlist.sub)
plot(xlist.sub)

It is enough to remove all the columns from the data frame that have a node with a number smaller than 5 as their root. It is important that you do the subsetting before applying graph.data.frame.

Upvotes: 1

Related Questions