NetworkX:基于节点颜色的颜色代码边 [英] NetworkX: color code edges based on node color

查看:72
本文介绍了NetworkX:基于节点颜色的颜色代码边的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了networkX加权图(请参阅

I created a networkX weighted graph (refer to this question for the code) and I wanted to color code the edges based on node color. If two nodes are of the same color and connected I want their edge color to be one color, say red. Moreover, if the nodes aren't the same color but connected I want them to be a different color, say blue. Is there a way I could achieve this?

The code for the edges is as follows:

for edge in G.edges():
    source, target = edge
    rad = 0.35
    arrowprops=dict(lw=G.edges[(source,target)]['weight'],
                    arrowstyle="-",
                    color='blue',
                    connectionstyle=f"arc3,rad={rad}",
                    linestyle= '-',
                    alpha=0.6)
    ax.annotate("",
                xy=pos[source],
                xytext=pos[target],
                arrowprops=arrowprops
               )

解决方案

Here is an example for you. Edges are red if nodes differ and green if they are the same.

import numpy as np
import networkx as nx
import matplotlib.pyplot as plt

G = nx.fast_gnp_random_graph(10, 0.5)

node_colors = [random.choice(["blue", "black"]) for node in G.nodes()]
edge_colors = [
    "green" if node_colors[edge[0]] == node_colors[edge[1]] else "red"
    for edge in G.edges()
]

plt.figure()
coord = nx.spring_layout(G, k=0.55, iterations=20)
nx.draw_networkx_nodes(G, coord, node_color=node_colors)
nx.draw_networkx_edges(G, coord, edge_color=edge_colors)

这篇关于NetworkX:基于节点颜色的颜色代码边的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆