【发布时间】:2020-10-17 09:57:07
【问题描述】:
我创建了一个加权 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()
感谢您的帮助!
【问题讨论】:
标签: python matplotlib networkx