python - NetworkX:基于节点颜色的颜色代码边缘
问题描述
我创建了一个 networkX 加权图(有关代码,请参阅此问题),我想根据节点颜色对边缘进行颜色编码。如果两个节点的颜色相同并且相互连接,我希望它们的边缘颜色是一种颜色,比如红色。此外,如果节点的颜色不同但连接在一起,我希望它们是不同的颜色,比如蓝色。有没有办法我可以做到这一点?
边的代码如下:
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
)
解决方案
这是一个给你的例子。如果节点不同,则边缘为红色,如果它们相同,则为绿色。
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)
推荐阅读
- python - 当输入是列表时,在 seaborn 中对箱线图/小提琴图进行分组
- pyspark - DATABRICKS SparkException:在 awaitResult 中引发异常 - 无法显示数据帧
- primefaces - PrimeFaces confirmDialog 更改语言后不会显示
- apache-kafka - KafkaCat 和 Docker:消息太大
- javascript - Chart.js 雷达工具提示显示太多值
- apache-spark - Spark - 30 分钟通用窗口化
- python - 如何获得熊猫时间范围的平均值
- pandas - 使用日期合并/连接非唯一多索引
- java - Spring Boot,JPA / Hibernate:如何一次执行两个原始 SELECT 查询?
- reactjs - 从函数返回反应组件的问题