在随机networkx图形中设置不同的节点颜色

2024-04-20 00:26:01 发布

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

我想让Erdős-Rényi随机图有100个节点,但我想用不同的节点颜色绘制这个图。例如,我希望有25个节点被涂成红色,25个节点被涂成蓝色,依此类推。你能帮助我吗,我如何在我的代码中实现这一点

>>> import networkx as nx
>>> import matplotlib.pyplot as plt
>>> G = nx.erdos_renyi_graph (100,0.02)
>>> nx.draw(G, node_color=range(100), node_size=800, cmap=plt.cm.Blues)

Tags: 代码importnetworkxnode节点matplotlib颜色as
1条回答
网友
1楼 · 发布于 2024-04-20 00:26:01

这可以通过使用来自matplotlib colors API的颜色来实现。从networkx.draw文档中,我们可以看到node_color的描述如下:

node_color (color or array of colors (default=’#1f78b4’))

Node color. Can be a single color or a sequence of colors with the same length as nodelist. Color can be string, or rgb (or rgba) tuple of floats from 0-1. If numeric values are specified they will be mapped to colors using the cmap and vmin,vmax parameters. See matplotlib.scatter for more details.

因此,在您的例子中,您希望25个节点是一种颜色,25个节点是另一种颜色,等等。为此,我们可以使用colors = ['r','b','y','c']*25定义颜色数组,然后将其传递给nx.draw,如下代码所示

代码:

import networkx as nx
import matplotlib.pyplot as plt
G = nx.erdos_renyi_graph (100,0.02)

colors = ['r','b','y','c']*25

plt.figure(figsize=(10,10))
nx.draw(G, node_size=400, node_color=colors, dpi=500)

输出:

Output graph

相关问题 更多 >