注意
Go to the end 下载完整示例代码。
视觉样式
此示例展示了如何更改网络图的视觉样式。
import igraph as ig
import matplotlib.pyplot as plt
import random
要配置图表的视觉样式,我们可以创建一个包含我们想要自定义的各种设置的字典:
visual_style = {
"edge_width": 0.3,
"vertex_size": 15,
"palette": "heat",
"layout": "fruchterman_reingold"
}
让我们看看它的实际效果!首先,我们生成四个随机图:
random.seed(1)
gs = [ig.Graph.Barabasi(n=30, m=1) for i in range(4)]
然后,我们为所有节点计算一个0-255之间的颜色颜色,例如使用介数作为示例:
betweenness = [g.betweenness() for g in gs]
colors = [[int(i * 255 / max(btw)) for i in btw] for btw in betweenness]
最后,我们可以使用相同的视觉风格为所有图形绘制图表:

注意
如果你想设置全局默认值,例如,总是使用Matplotlib绘图后端,或默认使用特定的调色板,你可以使用igraph的配置实例:class:`igraph.configuration.Configuration。关于如何使用它的快速示例可以在这里找到:配置实例。
在matplotlib后端中,igraph创建了一个特殊的容器
igraph.drawing.matplotlib.graph.GraphArtist,它是一个matplotlib Artist
并且是目标Axes的第一个子对象。该对象可用于在初始绘图后自定义
绘图外观,例如:
g = ig.Graph.Barabasi(n=30, m=1)
fig, ax = plt.subplots()
ig.plot(g, target=ax)
artist = ax.get_children()[0]
# Option 1:
artist.set(vertex_color="blue")
# Option 2:
artist.set_vertex_color("blue")
plt.show()

注意
igraph.drawing.matplotlib.graph.GraphArtist.set() 方法可以用于一次性更改多个属性,通常比多次调用特定的 artist.set_... 方法更高效。
在matplotlib后端中,您还可以指定自环的大小,可以是一个数字或一系列数字,例如:
g = ig.Graph(n=5)
g.add_edge(2, 3)
g.add_edge(0, 0)
g.add_edge(1, 1)
fig, ax = plt.subplots()
ig.plot(
g,
target=ax,
vertex_size=20,
edge_loop_size=[
0, # ignored, the first edge is not a loop
30, # loop for vertex 0
80, # loop for vertex 1
],
)
plt.show()

脚本的总运行时间: (0 分钟 4.699 秒)