如何使用图表工具的CSV文件数据在Python中创建图表?

时间:2016-10-10 09:03:46

标签: python csv graph-tool

我正在尝试使用csv文件中的图形工具(https://graph-tool.skewed.de)创建一个图形,内容如下:

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

现在我想创建一个图形,其中A,B,C,D作为节点,第三列编号作为边。我正在使用图形工具库。第三列编号显示A,B和A,C等共享的公共项目。

我可以通过“networkx”(read_edgelist等)来实现,但我想用图形工具来做。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

假设您已经知道如何在Python中阅读CSV文件(例如,使用CSV library),网站上的文档explain how to do this very clearly.

这样的东西
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]])