NetworkX - Connected Columns

369 Views Asked by At

I'm trying to create a data visualization, and maybe NetworkX isn't the best tool but I would like to have parallel columns of nodes (2 separate groups) which connect to each other. I can't figure out how to place the two groups of nodes in this layout. The different options I have tried always default to a more 'web-like' layout. I'm trying to create a visualization where customers/companies (the keys in a dictionary) would have edges drawn to product nodes (values in the same dictionary).

For example:

d = {"A":[ 1, 2, 3], "B": [2,3], "C": [1,3]

From dictionary 'd', we would have a column of nodes ["A", "B", "C"] and second column [1, 2, 3] and between the two edges would be drawn.

A                   1
B                   2
C                   3

UPDATE:

So the 'pos' argument suggested helped but I thought it was having difficulties using this on multiple objects. Here is the method I came up with:

nodes = ["A", "B", "C", "D"]
nodes2 = ["X", "Y", "Z"]

edges = [("A","Y"),("C","X"), ("C","Z")]

#This function will take a list of values we want to turn into nodes
# Then it assigns a y-value for a specific value of X creating columns
def create_pos(column, node_list):
    pos = {}
    y_val = 0
    for key in node_list:   
        pos[key] = (column, y_val)
        y_val = y_val+1
    return pos 



G.add_nodes_from(nodes)
G.add_nodes_from(nodes2)
G.add_edges_from(edges)

pos1 = create_pos(0, nodes)
pos2 = create_pos(1, nodes2)
pos = {**pos1, **pos2}

nx.draw(G, pos)
1

There are 1 best solutions below

0
James Gregorie On

Here is the code I wrote with the help of @wolfevokcats to create columns of nodes which are connected.

G = nx.Graph()

nodes = ["A", "B", "C", "D"]
nodes2 = ["X", "Y", "Z"]

edges = [("A","Y"),("C","X"), ("C","Z")]

    #This function will take a list of values we want to turn into nodes
    # Then it assigns a y-value for a specific value of X creating columns
def create_pos(column, node_list):
    pos = {}
    y_val = 0
    for key in node_list:   
        pos[key] = (column, y_val)
        y_val = y_val+1
    return pos 



G.add_nodes_from(nodes)
G.add_nodes_from(nodes2)
G.add_edges_from(edges)

pos1 = create_pos(0, nodes)
pos2 = create_pos(1, nodes2)
pos = {**pos1, **pos2}

nx.draw(G, pos, with_labels = True)