在SageMath中在图的顶点上绘制非内射标签



我有一个图,它的顶点由一些对(a,b(标记。我能以这样一种方式绘制它吗;a";打印在每个顶点上?我不能只是重新标记,因为我的地图(a,b(->a不是内射的。

举个小例子,以为例

G = Graph()
G.add_edge((1,1),(1,2))

通常的G.plot()给出(1,1(---(1,2(。相反,如何只生产1--1?

用非内射顶点labals绘制Sage图

我们描述了一个略显乏味的解决方法,然后一种恢复我们舒适的方式。

顶点的新类

一种解决方案是为顶点编写一个新类从tuple继承并具有自定义__str__方法只返回元组中第一个条目的字符串。

class MyVertex(tuple):
r"""
Class for vertices for special plotting of graphs.
Use with tuples, and only the first entry in the tuple
will be used as a vertex label when plotting the graph.
"""
def __init__(self, v):
self.vertex = v
def __str__(self):
return str(self.vertex[0])

使用它来定义图的顶点,我们获得了想要的行为。

定义一个图,并将(1, 1)的边添加到(1, 2):

sage: G = Graph()
sage: G.add_edge(MyVertex((1, 1)), MyVertex((1, 2)))

绘制图形时,两个顶点都具有标签1

sage: G.plot()
Launched png viewer for Graphics object consisting of 4 graphics primitives

列出顶点时,它们仍然完全显示:

sage: G.vertices()
[(1, 1), (1, 2)]

使用常用图形

为了避免必须显式使用MyVertex,我们编写了一个绘图函数创建一个中间";MyVertex"-常用图形的样式副本为了密谋。

def plot_graph(G):
r"""
Return a plot of this graph with special vertex labels.
The graph vertices are assumed to be tuples. The plot
uses the first component of each tuple as a vertex label.
"""
E = [(MyVertex(a), MyVertex(b)) for (a, b) in G.edges(labels=False)]
return Graph(E).plot()

现在比较:

sage: G = graphs.Grid2dGraph(3, 4)
sage: G.plot()
Launched png viewer for Graphics object consisting of 30 graphics primitives
sage: plot_graph(G)
Launched png viewer for Graphics object consisting of 30 graphics primitives

最新更新