Search code examples
pythongraph-tool

Graph-tool edge_property to string


I've got a graph with edge weights. I looked around and found that I can use edge_properties to represent an edge weight. I do it like this:

edge_weight = g.new_edge_property("double")

for i in range(10):
    e = g.add_edge(i, i+1)
    edge_weight[e] = i

Now I want to print a graph from this with the given edge weights on the edges. Do you have any ideas how to do this? The only thing that I could come up is this:

edge_weight = g.new_edge_property("double")
edge_str_weight = g.new_edge_property("string")

for i in range(10):
    e = g.add_edge(i, i+1)
    edge_weight[e] = i
    edge_str_weight[e] = str(i)

graph_draw(g, edge_text=edge_str_weight, output="out.png")

It works, but it's quite redundant. Also if it's suggested to store the edge weight in an other structure or something, feel free to comment :)


Solution

  • In principle, there is no need create a different property, since a conversion to string will be made inside graph_draw(). However, graph-tool uses hexadecimal float notation by default, because it allows for a perfect representation. This is ideal for storing the values in a file, but not for displaying them. Therefore your approach is correct. You can perhaps do it more succinctly and efficiently using map_property_values():

    label = g.new_edge_property()
    map_property_values(edge_weight, label, lambda w: str(w))
    
    graph_draw(g, edge_text=label, output="out.png"))