【问题标题】:NetworkX: color code edges based on node colorNetworkX:基于节点颜色的颜色代码边缘
【发布时间】:2023-04-07 16:58:01
【问题描述】:

我创建了一个 networkX 加权图(有关代码,请参阅 this question),我想根据节点颜色对边进行颜色编码。如果两个节点的颜色相同并且连接,我希望它们的边缘颜色是一种颜色,比如红色。此外,如果节点的颜色不同但连接在一起,我希望它们是不同的颜色,比如蓝色。有什么方法可以实现吗?

边缘的代码如下:

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
               )

【问题讨论】:

    标签: python matplotlib networkx


    【解决方案1】:

    这是一个给你的例子。如果节点不同,则边缘为红色,如果它们相同,则为绿色。

    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)
    

    【讨论】:

    • 得到以下错误:for edge in G.edges() TypeError: list indices must be integers or slices, not str
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多