Bi colored graph


Author: GC

Date: June 29, 2016

Previous Lorenz attractor

Next Hénon map


We draw a bi colored graph with the NetworkX library. The positions of the vertices are randomly generated. We run path finding algorithms to detect isolated nodes.



Bi colored graph




Source code

#!/usr/bin/env python3

"""
Program to draw a bi colored graph with NetworkX
"""


# scientific libraries
from matplotlib import pyplot as plt
import networkx as nx
from random import randint, random
import numpy as np

# vertices and edges
N = 120
Nred = 35
rednodes = range(Nred)
Ngreen = 85
greennodes = range(Nred, Nred+Ngreen)

Nedges = 100
edges = []
for k in range(Nedges):
    a, b = 0, 0
    while a==b:
        a, b = randint(0, N-1), randint(0, N-1)
    c = randint(1, 2)
    if c==1:
        edges = edges + [(a,b)]
    else:
        edges = edges + [(b,a)]


# graph generation
G = nx.DiGraph()
G.add_nodes_from(rednodes)
G.add_nodes_from(greennodes)
G.add_edges_from(edges)


# positions
pos = {}
for i in greennodes:
    pos.update({i: [0.5+1.1*np.cos(i)+randint(-15, 15)*0.02, 0.5+1.3*np.sin(i)+0.02*randint(-15, 15)]})
pos2 = nx.random_layout(rednodes)
pos.update(pos2)

# colors
edges_colors = range(G.number_of_edges())
greennodes_colors = []

for i in range(Ngreen):
    DE = randint(1, 4)
    if DE == 1:
        greennodes_colors = greennodes_colors + ['#22B04C']
    elif DE == 2:
        greennodes_colors = greennodes_colors + ['#54CA77']
    elif DE == 3:
        greennodes_colors = greennodes_colors + ['#008000']
    else:
        greennodes_colors = greennodes_colors + ['#4CC04C']
        
rednodes_colors = []

for i in range(Nred):
    DE = randint(1, 4)
    if DE == 1:
        rednodes_colors = rednodes_colors + ['#FF0000']
    elif DE == 2:
        rednodes_colors = rednodes_colors + ['#FFA500']
    elif DE == 3:
        rednodes_colors = rednodes_colors + ['#FF6800']
    else:
        rednodes_colors = rednodes_colors + ['#FF004E']

# path finding

isolated_nodes_number = 0
isolated_nodes_list = []
for k in range(Nred):
    connection = 0
    for j in range(Nred, Nred+Ngreen):
        if nx.has_path(G, k, j):
            connection = connection + 1
    if connection==0:
        print('Node ', k, 'is isolated.')
        isolated_nodes_number = isolated_nodes_number + 1
        isolated_nodes_list = isolated_nodes_list + [k]

print('Isolated nodes :', isolated_nodes_list)

# figure
fig, ax = plt.subplots(figsize=(8,8))
nx.draw_networkx_nodes(G, pos, node_size=65, nodelist=greennodes, node_color=greennodes_colors)
nx.draw_networkx_nodes(G, pos, node_size=65, nodelist=rednodes, node_color=rednodes_colors)
nx.draw_networkx_edges(G, pos, width=0.2, edge_color='0.2', alpha=0.7)
ax.axis('off')
plt.show()


Previous Lorenz attractor

Next Hénon map