根据NetworkX中的节点颜色对边缘进行颜色编码

时间:2020-10-17 09:57:07

标签: python matplotlib networkx

我创建了一个加权NetworkX图,用于分析个人之间的关系。我一直在使用this code为基于节点颜色的边缘着色,但是我一直遇到以下错误:

for edge in G.edges()
TypeError: string indices must be integers

关于我为什么会出现此错误的任何想法?

我的代码看起来像这样,但边缘没有颜色编码:

import matplotlib.pyplot as plt
import networkx as nx

G = nx.Graph()

G.add_edge("Ted", "May", weight=0.5)
G.add_edge("Ted", "Ray", weight=1)
G.add_edge("Ted", "Chris", weight=1)
G.add_edge("Ted", "Sam", weight=3)
G.add_edge("Ted", "April", weight=1)
G.add_edge("Ted", "Ana", weight=0)


G.add_edge("Ana", "Ryan", weight=1)
G.add_edge("Ana", "Jim", weight=0.5)
G.add_edge("Ana", "Ben", weight=1)

ops = ['Ana', 'Ryan']
mkt = ['Jim', 'Chris']
hr = ['Sam', 'April', 'Ben', 'Ray', 'Ted', 'May']

for0 = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] == 0]
for05 = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] == 0.5]
for1 = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] == 1]
for15 = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] == 1.5]
for3 = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] == 3]

pos = nx.circular_layout(G)  # positions for all nodes
ax=plt.gca()
# nodes
sc = nx.draw_networkx_nodes(G, pos, node_size=700)

# edges
for edge in G.edges():
    source, target = edge
    rad = 0.2
    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
               )

for n in G.nodes():
    if n in ops:
        G.nodes[n]['color'] = '#7a8eff'
    elif n in mkt:
        G.nodes[n]['color'] = '#eb2c30'
    else:
        G.nodes[n]['color'] = '#730a15'

colors = [node[1]['color'] for node in G.nodes(data=True)]
nx.draw_networkx_nodes(G, pos, node_size=1200, node_color=colors)

# labels
nx.draw_networkx_labels(G, pos, font_size=20, font_family="sans-serif")


plt.show()

谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

在链接中,节点是整数,但您的节点是字符串,因此您为sourcetarget定义的值不能用于索引列表。但是,您可以获得由节点名称(例如node_color_dict = dict(G.nodes(data='color')))键入的节点颜色的字典。对于你的图,你得到

{'Ana': '#7a8eff', 'April': '#730a15', 'Ben': '#730a15', 'Chris': '#eb2c30',
 'Jim': '#eb2c30', 'May': '#730a15', 'Ray': '#730a15', 'Ryan': '#7a8eff',
 'Sam': '#730a15', 'Ted': '#730a15'}

然后,您可以修改链接的代码以获取如下边缘颜色:

edge_colors = [
    "green" if node_color_dict[source] == node_color_dict[target] else "red"
    for source,target in G.edges()
]