0

I want to visualise a network, such that the nodes are aligned on a vertical axis based on a variable of each node. It's a little hard to explain, but here is a (low quality) image What I am looking for

So each node has a value, and the graph is visualised so these values align on the vertical axis. In the image above, the green nodes have value between 0 and 1, the blue nodes have value between 1 and 2, the yellow nodes have value of at least 2.

Any ideas how I can acheive this in Python, if I satrt with an adjacency matrix?

chasmani
  • 2,362
  • 2
  • 23
  • 35
  • Is it a tree by any chance? – Joel Jul 06 '19 at 04:19
  • Not necessarily a tree, there can be cycles – chasmani Jul 06 '19 at 18:58
  • This answer may help some: https://stackoverflow.com/questions/29586520/can-one-get-hierarchical-graphs-from-networkx-with-python-3/29597209#29597209. But it assumes a tree. A modification that allows cycles is available in another answer there. – Joel Jul 08 '19 at 01:29

1 Answers1

1

You can use the library NetworkX to create your graph and matplotlib to display it.

How to create a simple graph:

import networkx as nx

graph = nx.Graph()
graph.add_node('A')
graph.add_node('B')
graph.add_node('C')

graph.add_edge('A', 'B')
graph.add_edge('B', 'C')
graph.add_edge('A', 'C')

Then you can display it:

import matplotlib.pyplot as plt
plt.figure()
nx.draw(graph, with_labels=False)
plt.show()

You can also change the vertical position of the nodes when drawing them by passing the argument pos to nx.draw

nx.draw(graph, with_labels=False, pos={'A':(0, 0), 'B':(0,3), 'C':(2,3)})

Check the docs of nx.draw parameters: https://networkx.github.io/documentation/stable/reference/generated/networkx.drawing.nx_pylab.draw_networkx.html#networkx.drawing.nx_pylab.draw_networkx

Remember also to set your figure boundaries using plt.xlim() and plt.ylim()

Victor Ruiz
  • 1,192
  • 9
  • 9
  • 1
    Thanks for your answer. So I can set the y-co-ordinates based on my variable, but I kind of wanted the x-coordinates to be generated in some kind of intelligent way – chasmani Jul 05 '19 at 15:50
  • iterate over each node. Generate x-coord depending on the node id – Victor Ruiz Jul 05 '19 at 16:32