如何将图形中的边着色为

2024-04-19 21:21:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在Sage中绘制一个边颜色不同的图 根据他们是否满足某种条件。什么都没有 到目前为止,我阅读的文档中有关于 着色图的特定边。你知道吗

我不知道什么函数可以做到这一点,但我已经设置了 代码升级,我将显示:

for edge in g.edges()
    if edge[2] == -1:
        edge = ? # not sure how to change color of the edge

Tags: 函数代码in文档forif颜色绘制
1条回答
网友
1楼 · 发布于 2024-04-19 21:21:10

用不同的颜色绘制不同的边缘是圣人的天性!你知道吗

请参阅edge_coloredge_colors方法的可选参数plot 中的图形打印选项表中列出的图形 "Graph plotting" page of the SageMath reference manual 这个例子说“这个例子展示了边的颜色”。你知道吗

另请参见示例 the ^{} method of graphs。你知道吗

为了说明实现所需着色的一种方法, 从彼得森图开始,用 如果它们连接不同奇偶性的顶点,则为1,否则为-1。你知道吗

sage: g = graphs.PetersenGraph()
sage: for u, v, c in g.edge_iterator():
....:     g.set_edge_label(u, v, (u - v) % 2 - (u - v + 1) % 2)
....:

观察结果:

sage: g.edges()
[(0, 1, 1),
 (0, 4, -1),
 (0, 5, 1),
 (1, 2, 1),
 (1, 6, 1),
 (2, 3, 1),
 (2, 7, 1),
 (3, 4, 1),
 (3, 8, 1),
 (4, 9, 1),
 (5, 7, -1),
 (5, 8, 1),
 (6, 8, -1),
 (6, 9, 1),
 (7, 9, -1)]

要相应地绘制蓝色或红色的边,请执行以下操作:

sage: red_edges = [e for e in g.edge_iterator() if e[2] == -1]
sage: g.plot(edge_color='blue', edge_colors={'red': red_edges})
Launched png viewer for Graphics object consisting of 26 graphics primitives

Petersen graph colored by parity

我们也可以这样做:

sage: blue_edges = [e for e in g.edge_iterator() if e[2] != -1]
sage: red_edges = [e for e in g.edge_iterator() if e[2] == -1]
sage: g.plot(edge_colors={'blue': blue_edges, 'red': red_edges})
Launched png viewer for Graphics object consisting of 26 graphics primitives

这个答案的其余部分解释了我们如何用手来做这件事: 为每个边颜色创建一个子图,然后将这些子图绘制在一起。你知道吗

要说明这一点,请从彼得森图开始,并为边着色 取决于它们是否在相同奇偶校验的顶点之间。你知道吗

sage: g = graphs.PetersenGraph()

sage: a = copy(g)  # edges between vertices of different parity
sage: b = copy(g)  # edges between vertices of same parity

sage: for u, v, c in g.edge_iterator():
....:     if (u - v) % 2:
....:         b.delete_edge(u, v)
....:     else:
....:         a.delete_edge(u, v)

sage: pa = a.plot(axes=False, edge_color='blue')
sage: pb = b.plot(axes=False, edge_color='red')
sage: p = pa + pb
sage: p.show()
Launched png viewer for Graphics object consisting of 37 graphics primitives

Petersen graph colored by parity

保存绘图:

sage: p.save('Petersen_graph_by_parity.png')

对于原始问题,使用if c == -1而不是 if (u - v) % 2决定是从b还是从a删除边。 另外,Petersen图已经设置了顶点位置, 这个问题中的图g可能不是这样, 在这种情况下,将定义papb的两行替换为:

sage: pa = a.plot(axes=False, edge_color='blue', save_pos=True)
sage: pb = b.plot(axes=False, edge_color='red', pos=pa.get_pos())

这个答案的灵感来自 Thierry Monteil's answer 类似的问题:

相关问题 更多 >