我正在尝试使用库图形工具来创建对象的新图形。我特别希望有学生和教授的某些节点。
在下面编写的代码中,我无法添加学生/教授的顶点。
文档https://graph-tool.skewed.de/static/doc/quickstart.html#property-maps解释说我必须使用PropertyMap类,这对我来说很奇怪...
有人可以向我解释如何使用它吗?谢谢。
这是我的代码:
from graph_tool.all import *
class Student:
def __init__(self, name):
self.name = name
class Professor:
def __init__(self, name):
self.name = name
g = Graph()
s = Student("Luke")
p = Professor("Adam")
print(s.name)
print(p.name)
答案 0 :(得分:0)
首先,您需要将顶点添加到图中
# your code
# from graph_tool.all import * # avoid importing all, it makes it inclear what you are using afterwards
import graph_tool as gt
class Student:
def __init__(self, name):
self.name = name
class Professor:
def __init__(self, name):
self.name = name
g = gt.Graph()
s = Student("Luke")
p = Professor("Adam")
print(s.name)
print(p.name)
Luke
Adam
您为用户类型创建一个属性映射
g.vertex_properties['user_type'] = g.new_vertex_property('string')
这将是您节点的属性。您可以创建所需数量,然后设置其user_type 例如:
# creating a graph of 3 users
g.add_vertex(3)
# Let's set the first vertex as a professor
g.vp['user_type'][g.vertex(0)] = 'professor'
# and the subsequent as students
for v in g.get_vertices()[1:]:
g.vp['user_type'][v] = 'student'
# let's add an edge from the professor to the first student
g.add_edge(g.vertex(0), g.vertex(1))
<Edge object with source '0' and target '1' at 0x7f2c30370c30>
现在您可以使用该属性绘制图形
def translate_elts_to_gtshape(g, source_prop='user_type', tdict=None):
"""This function adds a new property map called 'shape' to graph g. It is populated by translating the source_prop with the tdict (translation dictionnary) which should map source_property entries to shapes"""
if tdict is None:
tdict = {'professor': 'square',
'student': 'circle'}
# source_property map array. It's of string type so we use get_2d_array
svp = g.vp[source_prop].get_2d_array([0])[0]
for k, v in tdict.items():
# for each key, value pair of tdict we change the source value (ie k) to the shape (v)
svp[svp == k] = v
# and now we create the new property shape
g.vertex_properties['shape'] = g.new_vertex_property('string')
for v, p in zip(g.vertices(), svp):
# and copy in it the shape
g.vp['shape'][v] = p
# we return the new property created, although it is already added to the graph as an internal property
return g.vp['shape']
translate_elts_to_gtshape(g)
<PropertyMap object with key type 'Vertex' and value type 'string', for Graph 0x7f2c5c3d6510, at 0x7f2c2997c950>
# let's just check what we have in our newly created shape property
[g.vp['shape'][v] for v in g.vertices()]
['square', 'circle', 'circle']
# and now let's use it to draw our graph
import graph_tool.draw as gtd
pos = gtd.sfdp_layout(g)
gtd.graph_draw(g, pos=pos,
output_size = (300, 300),
output_file = 'mynetwork.png', # where your file goes
vertex_shape=g.vp['shape'],
vertex_text=g.vertex_index)
<PropertyMap object with key type 'Vertex' and value type 'vector<double>', for Graph 0x7f2c5c3d6510, at 0x7f2c14291590>