问题
I have created a directed graph and through a program i am finding out all the cycles it contains. After creating the graph i want to change the colour of the edges which contain the vertices involved in the cycle.
I am using python igraph.
Please Help
回答1:
Something like this:
vertex_set = set(vertices_in_cycle)
g.es["color"] = "black"
red_edges = g.es.select(_source_in=vertex_set, _target_in=vertex_set)
red_edges["color"] = "red"
Explanation:
g.esrepresents the set of all edges in the graph. (Similarly,g.vsis the set of all vertices).g.es["color"]lets you assign a value to thecolorattribute of all the edges in the graph. This edge attribute is used by the plotter to decide what color an edge should have. Therefore, in line 2, you are setting the color of all the edges to black. (Note: you could also use a list here instead of a simple string, or you could use HTML color notations for custom colors).You could use
g.esas a list, in which case you get a particular edge of the graph; e.g.,g.es[2]would give you the edge with id=2. This is not used here, but it's good to know.g.es.selectis a method that selects a subset of the edges based on some criteria.help(EdgeSeq.select)gives you more info about this; the point here is that in line 3, you are selecting all the edges for which both endpoints lie in the vertex set you are interested in. The selected edges are stored in thered_edgesvariable, which has the same type asg.es(i.e.EdgeSeq).In the last row, you are setting the color of all the edges in
red_edgestored, overriding the black color you have set in line 2.
Note that the above code will paint not only the edges of the cycle to red but also all the chords of the cycle.
Update: if line 3 in the above code does not work for you for some reason, you can replace lines 2 and 3 with the following:
g.es["color"] = ["red" if (edge.source in vertex_set and \
edge.target in vertex_set) else "black" \
for edge in g.es]
来源:https://stackoverflow.com/questions/10067721/can-i-change-the-colour-of-edges-containing-specific-vertices-in-igraph-python