【问题标题】:Color coding edges based on node color in NetworkX基于 NetworkX 中节点颜色的颜色编码边缘
【发布时间】: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


    【解决方案1】:

    在链接中,节点是整数,但您的节点是字符串,因此您为 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()
    ]
    

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      相关资源
      最近更新 更多