nandz123
nandz123

Reputation: 169

NetworkX: color code edges based on node color

I created a networkX weighted graph (refer to this question for the code) and I wanted to color code the edges based on node color. If two nodes are of the same color and connected I want their edge color to be one color, say red. Moreover, if the nodes aren't the same color but connected I want them to be a different color, say blue. Is there a way I could achieve this?

The code for the edges is as follows:

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
               )

Upvotes: 0

Views: 1033

Answers (1)

ilia
ilia

Reputation: 640

Here is an example for you. Edges are red if nodes differ and green if they are the same.

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)

resulting graph

Upvotes: 1

Related Questions