有向图和上一篇介绍的无向图基本一样,唯一的区别在于有向图的边有方向性,它表示的是顶点之间的单向或依赖关系。

有向图G一般表示为:G=<V,E>。和无向图一样,V是顶点集合,E是边的集合。

不同之处在于,无向图是用小括号(V,E),有向图用尖括号<V,E>。

在有向图中,边是有方向的,所以,从顶点A到顶点B的边与从顶点B到顶点A的边是不同的。

与无向图一样,有向图也有很多应用场景,比如:

在地图导航中,有向图常被用来表示道路网络。

节点代表地点(如交叉路口、城市等),有向边代表道路,边的权重可以表示道路的长度、行驶时间或交通状况等。

在供应链管理中,有向图可以用来表示货物的流动路径。

节点代表供应链中的各个环节(如供应商、制造商、分销商等),边代表货物流动的路径,边的容量可以表示货物的承载能力。

在社会网络中,上一篇提到可以用无向图表示用户之间的好友关系。

而有向图同样可以用在社会网络分析,它可以用来表示用户之间的关注关系,转发关系等,用于分析用户的行为模式。

下面介绍manim中绘制有向图的对象DiGraph。

1. 主要参数

有向图对象DiGraph主要参数和无向图类似:

参数名称 类型 说明
vertices list 图的顶点列表
edges list 图的边列表,每个边
labels dict 顶点是否显示标签文本
label_fill_color str 标签的背景色
layout str 图中定点的布局方式
layout_config dict 配置如何布局图中各个顶点
layout_scale float 图各个顶点布局的比例
vertex_type Mobject 顶点的类型,不一定是点,也可以是manim中其他的对象
vertex_config dict 顶点相关的配置
vertex_mobjects dict 一系列的顶点对象
edge_type Mobject 边的类型,不一定是线,也可以是manim中其他的对象
edge_config dict 边相关的配置
partitions list
root_vertex dict

这些参数中,vertices和edges相关的参数(比如xxx_type,xxx_config)比较好理解。

labels参数设置是否需要显示顶点的标签,默认是把vertices的数值作为标签的内容。

layout参数内置了多种现成的布局方式:

  • 'circular',
  • 'kamada_kawai'
  • 'partite'
  • 'planar'
  • 'random'
  • 'shell'
  • 'spectral'
  • 'spiral'
  • 'spring'
  • 'tree'

layout_config参数可以对上面现成布局方式的进行微调。

最后两个参数partitions和root_vertex比较特殊,

partitions只能在layout设置为'partite'时使用,用来生成层状的图(比如描述神经网络的图),

partitions用来设置每一层包含哪些顶点;

root_vertex只能在layout设置为'tree'时使用,用来树状图,

root_vertex用来设置树的根节点。

后面的示例会演示如何使用partitions和root_vertex来生成层状和树状的有向图。

2. 主要方法

有向图DiGraph的方法主要用来动态改变有向图,比如添加或删除顶点和边。

名称 说明
add_edges 增加有向图的边
add_vertices 增加有向图的顶点
remove_edges 删除有向图的边
remove_vertices 删除有向图的顶点
change_layout 动态改表有向图的结构
from_networkx 从networkx来生成有向图

networkx是另一个常用的Python库,用于创建、操作和研究复杂网络的结构。

DiGraph对象也可以直接根据networkx的对象生成图。

3. 使用示例

下面的示例和上一篇无向图的示例类似,只是改用有向图DiGraph对象来实现。

3.1. 顶点的配置

顶点的设置和无向图几乎是一样的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from manim import *
FONT = "STLiti"
V = [0, 1, 2]
E = [(0, 1), (0, 2), (1, 2)]
LAB = {i: Text(str(i), font=FONT, font_size=28, color=BLACK) for i in V}
class DiGraphExample(Scene):
def construct(self):
head = Text("顶点的配置:颜色 / 标签 / 星形", font=FONT, font_size=32, color=YELLOW).to_edge(UP)
g1 = DiGraph(V, E, layout="circular", layout_scale=1.0,
vertex_config={0: {"color": RED}, 1: {"color": GREEN}, 2: {"color": BLUE}})
g2 = DiGraph(V, E, layout="circular", layout_scale=1.0,
labels=LAB, vertex_config={"color": WHITE, "radius": 0.28})
g3 = DiGraph(V, E, layout="circular", layout_scale=1.0,
vertex_type=Star, vertex_config={"outer_radius": 0.22, "color": YELLOW})
row = Group(g1, g2, g3).arrange(RIGHT, buff=1.8).scale(1.25)
caps = Group(*[Text(s, font=FONT, font_size=24, color=YELLOW_C) for s in
("不同颜色的顶点", "带标签的顶点", "星形的顶点")])
for i, cap in enumerate(caps):
cap.next_to(row[i], DOWN, buff=0.45)
self.add(head)
self.play(FadeIn(g1), FadeIn(caps[0]), run_time=1.0)
self.play(FadeIn(g2), FadeIn(caps[1]), run_time=1.0)
self.play(FadeIn(g3), FadeIn(caps[2]), run_time=1.0)
self.wait(2.6)

下载 Python 脚本

3.2. 边的配置

有向图的边也和顶点一样,可以设置颜色,粗细等属性,

与无向图不同之处在于:有向图的边可以设置箭头的样式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from manim import *
FONT = "STLiti"
V = [0, 1, 2]
E = [(0, 1), (0, 2), (1, 2)]
class DiGraphExample(Scene):
def construct(self):
head = Text("边的配置:颜色 / 粗细 / 箭头", font=FONT, font_size=32, color=YELLOW).to_edge(UP)
g1 = DiGraph(V, E, layout="circular", layout_scale=1.0,
edge_config={(0, 1): {"color": RED}, (0, 2): {"color": GREEN},
(1, 2): {"color": BLUE}})
g2 = DiGraph(V, E, layout="circular", layout_scale=1.0,
edge_config={(0, 1): {"stroke_width": 2}, (0, 2): {"stroke_width": 8},
(1, 2): {"stroke_width": 14}})
g3 = DiGraph(V, E, layout="circular", layout_scale=1.0,
edge_config={(0, 1): {"tip_config": {"tip_shape": ArrowCircleTip}},
(0, 2): {"tip_config": {"tip_shape": ArrowTriangleTip}},
(1, 2): {"tip_config": {"tip_shape": ArrowSquareTip}}})
row = Group(g1, g2, g3).arrange(RIGHT, buff=1.8).scale(1.25)
caps = Group(*[Text(s, font=FONT, font_size=24, color=YELLOW_C) for s in
("不同颜色的边", "不同粗细的边", "不同箭头的边")])
for i, cap in enumerate(caps):
cap.next_to(row[i], DOWN, buff=0.45)
self.add(head)
self.play(FadeIn(g1), FadeIn(caps[0]), run_time=1.0)
self.play(FadeIn(g2), FadeIn(caps[1]), run_time=1.0)
self.play(FadeIn(g3), FadeIn(caps[2]), run_time=1.0)
self.wait(2.6)

下载 Python 脚本

3.3. 内置的layout

有向图中内置的layout和上一篇无向图中介绍的是一样的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from manim import *
FONT = "STLiti"
V = [1, 2, 3, 4, 5, 6]
E = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 1), (5, 1), (1, 3), (3, 5)]
NAMES = ["spring", "circular", "kamada_kawai", "planar", "random", "shell", "spectral", "spiral"]
class DiGraphExample(Scene):
def construct(self):
head = VGroup(Text("DiGraph ", font="Consolas", font_size=32, color=YELLOW),
Text("内置的八种布局", font=FONT, font_size=32, color=YELLOW)).arrange(RIGHT, buff=0.1).to_edge(UP)
cards = []
for n in NAMES:
g = DiGraph(V, E, layout=n, layout_scale=0.75,
edge_config={"tip_config": {"tip_length": 0.12, "tip_width": 0.12}})
cap = Text(n, font="Consolas", font_size=20, color=GREEN).next_to(g, DOWN, buff=0.12)
cards.append(VGroup(g, cap))
Group(*cards).arrange_in_grid(rows=2, cols=4, buff=(0.9, 1.0)).scale(1.2)
self.add(head)
for c in cards:
self.play(FadeIn(c[0]), FadeIn(c[1]), run_time=0.45)
self.wait(2.0)

下载 Python 脚本

3.4. 层状图

层状图的布局需要配合参数partitions一起使用,partitions中决定每一层中有哪些顶点。

有向图的边有方向,绘制出来更像神经网络的结构。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from manim import *
FONT = "STLiti"
V = list(range(9))
E = [(0, 2), (0, 3), (0, 4), (1, 3), (1, 4), (2, 5), (2, 6), (3, 5),
(3, 6), (3, 7), (4, 6), (4, 8), (5, 7), (5, 8), (6, 7), (6, 8)]
PARTS = [[0, 1], [2, 3, 4], [5, 6], [7, 8]]
COL = [RED, GREEN, BLUE, YELLOW, PURPLE, ORANGE]
LAB = {i: Text(str(i), font=FONT, font_size=26, color=BLACK) for i in V}
class DiGraphExample(Scene):
def construct(self):
head = VGroup(Text("层状图:", font=FONT, font_size=32, color=YELLOW),
Text("partitions", font="Consolas", font_size=30, color=YELLOW),
Text(" 四层", font=FONT, font_size=32, color=YELLOW)).arrange(RIGHT, buff=0.08).to_edge(UP)
cfg = {ee: {"color": COL[i % len(COL)], "stroke_width": 6} for i, ee in enumerate(E)}
g = DiGraph(V, E, layout="partite", partitions=PARTS, layout_scale=3.0,
labels=LAB, vertex_config={"color": WHITE, "radius": 0.30},
edge_config=cfg).scale(1.2)
self.play(FadeIn(head), run_time=0.6)
self.play(FadeIn(VGroup(*g.vertices.values())), run_time=1.2)
self.play(Create(VGroup(*g.edges.values())), run_time=1.8)
self.wait(2.0)

下载 Python 脚本

3.5. 树状图

树状图的布局需要配合参数root_vertex一起使用,root_vertex定义了树的根顶点是哪个。

这里与无向图有个不同的地方,绘制有向的树状图时,顶点和边的顺序很重要,需要从根节点开始,依次传入各个顶点。

下面示例中,第二个树状图改变了根节点,不是仅仅改变root_vertex就行的,需要先改变图中顶点的顺序。

下面的代码是简略后的代码,完整的代码可以文中最后部分的链接中下载。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from manim import *
FONT = "STLiti"
V1 = [0, 1, 2, 3, 4, 5, 6, 7, 8]
E1 = [(0, 1), (0, 2), (0, 3), (1, 4), (1, 5), (2, 6), (2, 7), (3, 8)]
V2 = [2, 7, 6, 0, 3, 1, 8, 5, 4]
E2 = [(2, 7), (2, 6), (2, 0), (0, 3), (0, 1), (3, 8), (1, 5), (1, 4)]
COL = [YELLOW, RED, GREEN, BLUE, PURPLE, ORANGE, TEAL, MAROON]
CFG = {"color": WHITE, "radius": 0.30}
class DiGraphExample(Scene):
def construct(self):
lab1 = {i: Text(str(i), font=FONT, font_size=26, color=BLACK) for i in V1}
lab2 = {i: Text(str(i), font=FONT, font_size=26, color=BLACK) for i in V2}
ecfg1 = {e: {"color": COL[i % len(COL)], "stroke_width": 5} for i, e in enumerate(E1)}
ecfg2 = {e: {"color": COL[i % len(COL)], "stroke_width": 5} for i, e in enumerate(E2)}
g = DiGraph(V1, E1, layout="tree", root_vertex=0, layout_scale=3.0,
labels=lab1, vertex_config=CFG, edge_config=ecfg1).scale(1.2)
head = Text("root_vertex = 0", font="Consolas", font_size=30, color=YELLOW).to_corner(UL, buff=0.4)
self.play(FadeIn(head), FadeIn(g), run_time=1.4)
self.wait(0.8)
g2 = DiGraph(V2, E2, layout="tree", root_vertex=2, layout_scale=3.0,
labels=lab2, vertex_config=CFG, edge_config=ecfg2).scale(1.2)
head2 = Text("root_vertex = 2", font="Consolas", font_size=30, color=YELLOW).to_corner(UL, buff=0.4)
self.play(FadeOut(g), run_time=0.6)
self.remove(head)
self.play(FadeIn(head2), FadeIn(g2), run_time=1.4)
self.wait(1.6)

下载 Python 脚本

4. 附件

文中示例的完整脚本如下,与上方代码块、演示视频逐字一致;用 manim -qh 脚本.py 本地渲染即可复现。