python - 如何将图中的边着色为某种颜色

标签 python sage

我想在 Sage 中绘制一个边缘颜色不同的图表 根据他们是否满足某个条件。里面什么都没有 到目前为止我读过的文档包含以下信息 为图表的特定边着色。

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

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

最佳答案

Sage 内置了用不同颜色绘制不同边的功能!

查看 plot 方法的 edge_coloredge_colors 可选参数 图表绘制选项表中列出的图表数量 "Graph plotting" page of the SageMath reference manual 那里的例子说“这个例子展示了边缘的颜色”。

另请参阅示例 the set_edges method of graphs .

为了说明实现所需着色的一种方法, 从 Petersen 图开始,并用以下标记边缘 如果它们连接不同奇偶校验的顶点,则为 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
<小时/>

这个答案的其余部分解释了我们如何手动完成此操作: 为每个边缘颜色创建一个子图,然后将这些子图绘制在一起。

为了说明这一点,从 Petersen 图开始,并对边缘进行颜色处理 根据它们是否位于具有相同奇偶性的顶点之间而有所不同。

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 类似的问题:

关于python - 如何将图中的边着色为某种颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55768473/

相关文章:

python - 圣贤新手;在向量和矩阵中引入符号(变量)

python : "mutable vectors are unhashable"错误

sage - 如何在 SageMath 7.1 中加载文件

python - 避免(或加速)Python 中的大循环?

python - 按列分组并将多个聚合作为数据框返回

python - 如何解压pkl文件?

Python Tkinter Canvas 获取线的基本方向

python - 遍历圣人中矩阵的行

python - Jinja2 和 Json

python - 库定义中的导入语句似乎没有被执行