paulbrodersen / netgraph

Publication-quality network visualisations in python
GNU General Public License v3.0
660 stars 39 forks source link

How can I change the direction of a dot graph? #78

Closed evan54 closed 8 months ago

evan54 commented 8 months ago

https://netgraph.readthedocs.io/en/latest/sphinx_gallery_output/plot_08_dot_layout.html#sphx-glr-sphinx-gallery-output-plot-08-dot-layout-py

I'm using the dot node_layout and this starts from top to bottom creating a tree like structure - is it possible to have this be left to right instead?

paulbrodersen commented 8 months ago

Yes, but you will have to pre-compute the node positions and transform them manually.

Figure_1

import matplotlib.pyplot as plt
import networkx as nx

from netgraph import Graph, get_sugiyama_layout

unbalanced_tree = [
    (0, 1),
    (0, 2),
    (0, 3),
    (0, 4),
    (0, 5),
    (2, 6),
    (3, 7),
    (3, 8),
    (4, 9),
    (4, 10),
    (4, 11),
    (5, 12),
    (5, 13),
    (5, 14),
    (5, 15)
]

# Pre-compute node positions; the dot layout uses the Sugiyama algorithm.
node_positions = get_sugiyama_layout(unbalanced_tree)

# Swap x and y (top->bottom to right->left) and multiply the x  coordinate (formerly y) by -1 (right->left to left->right).
node_positions = {node : (-y, x) for node, (x, y) in node_positions.items()}

# Plot graph with pre-computed node positions.
fig, ax = plt.subplots()
Graph(unbalanced_tree, node_layout=node_positions, ax=ax)
plt.show()

I will close the issue for now; feel free to re-open if this solution does not work as expected.