1

I'm trying to create a graph with graph-tool (https://graph-tool.skewed.de) from csv file that content like:

A,B,50
A,C,34
C,D,55
D,D,80
A,D,90
B,D,78

Now I want to create a graph with A, B, C, D as nodes and the third column numbers as edges. I am using graph-tool library. The third column number shows the common items shared by A,B and A,C and so on.

I can do it by "networkx" (read_edgelist and etc) but I want to do it with graph-tool.

5
  • How general do you want your program to be? (i.e. do you want to plot any CSV file you pass it, or does it just have to be this one?) Could you post your code so far? Commented Oct 10, 2016 at 9:11
  • Actually, I done some code with networkx but I don't have any code with graph-tool ( I don't know how to start to read edge with graph-tool) Commented Oct 10, 2016 at 10:05
  • Specifically, have you already got the CSV parser working? i.e. do you already have something like [[A , B, 50], [A, C, 50]] in memory? Commented Oct 10, 2016 at 10:50
  • Yes, I can do it! Commented Oct 10, 2016 at 11:02
  • Possible duplicate of How to create a graph using a CSV File data? Commented Aug 24, 2018 at 2:05

2 Answers 2

2

You can use add_edge_list() to add a list of edges. If them are stored with names that differ from the index assigned automatically it will return a list of string containing the names from the list.

EXAMPLE:

from graph_tool.all import *
import csv

g=Graph(directed=False)
csv_E = csv.reader(open('*text_input*'))

e_weight=g.new_edge_property('float')
v_names=g.add_edge_list(csv_E,hashed=True,string_vals=True,eprops=[e_weight])  
#this will assign the weight to the propery map *e_weight* and the names to *v_names*

graph_draw(g, vertex_text=v_names)
Sign up to request clarification or add additional context in comments.

Comments

1

Assuming you already know how to read the CSV file in Python (for example, using the CSV library), The docs on the website explain how to do this very clearly.

Something like

import graph_tool
g = Graph(directed=False)


# this is the result of csv.parse(file)
list_of_edges = [['A', 'B', 50], ['A','C',34], ['C','D',55], ['D','D',80], ['A','D',90], ['B','D',78]]

vertices = {}

for e in list_of_edges:
    if e[0] not in vertices:
        vertices[e[0]] = True
    if e[1] not in vertices:
        vertices[e[1]] = True


for d in vertices:
    vertices[d] = g.add_vertex()

for edge in list_of_edges:
    g.add_edge(vertices[edge[0]], vertices[edge[1]])

1 Comment

Thanks, I tested and it's work, but what about if I want to show label in node instead of index number? I'm using this code to plot graph: graph_draw(g, vertex_text=g.vertex_index, vertex_font_size=18, output_size=(800, 800), output="two-nodes.png")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.