Plotting graph using edge list

Hi all.

I want to plot a SimpleDiGraph using an edge list and label the edges according to their position in my edge list. For example, if I run the following code

using Graphs, GraphPlot
edge_list = Edge.([ (1, 3), (3, 2), (1, 2)])
g = SimpleDiGraph(edge_list)
display(gplot(g, nodelabel = 1:3, edgelabel = ["a", "b", "c"]))

I want edge (1,3) to have label “a”, (3,2) label “b” and (1,2) label “c”. However, the labeling is changed automatically to the order of the edges as they appear in collect(edges(g)). How can I circumvent this behaviour?

Related question: suppose I have edge_list = Edge.([ (1, 3), (3, 2), (1, 100)]). Then the graph will get 100 vertices, while I only want to have four, i.e. vertex 1, 2, 3 and 100. Is there an easy way to construct a directed graph, with the correct amount of vertices (that are also correctly labeled), in such a case?

You can do something like this :
edges_to_label = Dict(Edge(1,3) => "a", Edge(3,2) => "b", Edge(1,2) => "c")
display(gplot(g, nodelabel = 1:3, edgelabel = [edges_to_label[e] for e in edges(g)]))

SimpleGraph only supports a unit range for the index of vertices, if you want to use your own labeling, you should use a MetaGraphs. (You can also have a look at MetaGraphsNext which is still experimental but should be more performant)

1 Like