python - Networkx:为图中的社区(节点)指定颜色

标签 python matplotlib networkx

我想为每个检测到的社区绘制一个带有彩色节点的网络(我已经有每个社区的节点列表。)

我现在有这样的东西:

plot = nx.draw(G3, nodecolor='r', node_color= 'white', edge_color='k',
         with_labels=True, font_weight='light', node_size= 280, width= 0.9)
plt.savefig('graphe.png')
plt.show()

如何以每个社区都采用特定颜色的方式实现它?

最佳答案

你很接近。您只需绘制一组节点,一次绘制一个社区。 另外,由于我们是一步一步绘制的,所以我们必须固定节点的位置。 为此,我们使用 nx.spring_layout()

这是一个可以帮助您跟进的工作示例,其中包含虚拟数据。

node_lists_community1 = [1,2,3, 4]
node_lists_community2 = [5, 6, 7]
node_lists_community3 = [8,10,11,12, 13]
all_nodes = node_lists_community1+ node_lists_community2+ node_lists_community3

#list of edges
elist = [(1,2), (1,3), (2,4), (2, 5), (5,6), (6,7),
        (7,9), (8,10), (8,11), (11,13), (12,13)]

#create the networkx Graph with node types and specifying edge distances
G3 = nx.Graph()
for n in all_nodes:
    G3.add_node(n)
for from_loc, to_loc in elist:
    G3.add_edge(from_loc, to_loc)   

pos = nx.spring_layout(G3) #calculate position for each node
# pos is needed because we are going to draw a few nodes at a time,
# pos fixes their positions.

# Notice that the pos dict is passed to each call to draw below

# Draw the graph, but don't color the nodes
nx.draw(G3, pos, edge_color='k',  with_labels=True,
         font_weight='light', node_size= 280, width= 0.9)

#For each community list, draw the nodes, giving it a specific color.
nx.draw_networkx_nodes(G3, pos, nodelist=node_lists_community1, node_color='b')
nx.draw_networkx_nodes(G3, pos, nodelist=node_lists_community2, node_color='r')
nx.draw_networkx_nodes(G3, pos, nodelist=node_lists_community3, node_color='g')

plt.savefig('graphe.png')
plt.show()

enter image description here

有什么不明白的请追问。

关于python - Networkx:为图中的社区(节点)指定颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50828284/

相关文章:

python - OpenCV Python QueryFrame 函数泄漏内存

python - 使用 matplotlib *没有* TCL

python - 交替合并不相等的两个列表

python - 在 networkx 中加载双邻接矩阵

Python NetworkX——根据属性选项的数量自动设置节点颜色

python - 如何在一个文件中存储多个networkx图?

javascript - 如何将 python OpenCV 输出流式传输到 HTML Canvas ?

python - Matplotlib - 提取 3D 多边形图的 2D 轮廓

python - 在绘图上显示数据框

python - matplotlib 中未显示绘图窗口