How to find subgraph of all ancestors of a node?

I have a graph which looks like this:
Now I want to generate a subgraph of node 2’s ancestors and node 2 itself, like networkx’s
G.subgraph({G.ancestors(2)|2}), but not only graph.subcomponents() but also graph.precessdors() can’t achieve this.
How can I accomplish it?

Can you define what you mean by “ancestor”?

NetworkX’s definition is:

Returns all nodes having a path to source in G.

This is precisely what subcomponent() does. Why are you saying that it cannot achieve it?

In [1]: import igraph as ig

In [2]: g = ig.Graph([(0,2),(1,2),(3,1),(2,4)], directed=True)

In [3]: g.subcomponent(2, mode='in')
Out[3]: [2, 0, 1, 3]

predecessors() returns only those vertices which have a direct (one-step) connection to the given vertex. In this case, these are only 0 and 1, but not 3.

In [6]: g.predecessors(2)
Out[6]: [0, 1]

The graph, for reference:

Yes,however graph.subcomponent() can only return a list,not a graph,networkx can give me a graph of itself.

That’s because the indices can be used more flexibly, and can be generated much faster, than a new graph. You can always construct a new graph for a subgraph explicitly, see the .induced_subgraph() method.

Note that the vertex indices will change in this subgraph, as they always go from 0 to vcount - 1 in igraph. You may want to give the vertices names, so you can refer to them in the same way in the original graph as in the subgraph.